views:

391

answers:

5

Hi, I am trying to upload files to my server using php to save them into a binary form into my mysql database but I cant get it to work, here is the script I’m using, I believe it has something to do with "$_FILES" because when I take this out "&& $_FILES['userfile']['size'] > 0" the script starts to run but then the variables underneath that use "$_FILES" aren’t defined.

if(isset($_POST['upload']) && $_FILES['userfile']['size'] >  0) {
$fileName = $_FILES['userfile']['name'];
$tmpName  = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

$fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);

if(!get_magic_quotes_gpc())
{
    $fileName = addslashes($fileName);
}

db_connect();
db_select();

$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";

mysql_query($query) or die('Error, query failed');
db_disconnect();

echo "<br>File $fileName uploaded<br>";
}

Thanks, Stanni

+1  A: 

I assume your field that's being posted is named "userfile"?

Also, this is not directly germane to your question, but it's generally considered a better practice to store files in the filesystem rather than in MySQL. Filesystems are designed to store large blocks of binary data, while databases are not.

Jeremy DeGroot
I was storing the files in a file system first off but tried this to make sure the error wanst something to do with the server not allowing uploads or something.
Ryan
+3  A: 

You should better use the file upload status to check whether the upload was successful.

And don’t use the addslashes function for MySQL queries. Use the mysql_real_escape_string instead.

Gumbo
+2  A: 

If you upload the files with a form, does it have a 'enctype="multipart/form-data"' in the "form" tag?

Carsten
+1  A: 

I assume from your example that your input name is upload. <input type="file" /> results in PHP are not sorted in $_POST but in $_FILES. The documentation uses $_FILES['userfile'] as their example field, but if your input is declared as <input type="file" name="upload" />, you should simply use $_FILES['upload'].

Andrew Moore
Nope this is my form code:<input type="hidden" name="MAX_FILE_SIZE" value="2000000"><input name="userfile" type="file" id="userfile">
Ryan
+2  A: 

This is a 2 fold process, first the upload itself and then the manipulation on the server. The first validation would be to make sure the file was even uploaded. For that you can use after the line

$fileName = $_FILES['userfile']['name'];

Use:

if(is_uploaded_file($fileName)) {
  // Here goes all the file manipulation/storage/etc
} else {
  echo 'Error: File could not be uploaded.';
}

Try to use that and maybe re-post if the file was actually uploaded. Just because $_FILES has content it does not necessarily mean that the file was uploaded to the server.

GiladG