Jump to content

file as blob in mysql through PHP


ogara

Recommended Posts

Hello,

I am storing files that my users upload to the website as a blob in mysql database. Here is the code that does uploading:

$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 = mysql_real_escape_string($content);

fclose($fp);

if(!get_magic_quotes_gpc())

{

$fileName = addslashes($fileName);

}

$query = mysql_query("INSERT INTO documents (idapplicant, fileType, fileSize, fileData, fileName)

VALUES ('$idapplicant','$fileType','$fileSize', '$content','$fileName')",$db);

 

Here is the code for download:

echo "File found:".@mysql_result($result, 0, "fileID"); //always correct

$data = @mysql_result($result, 0, "fileData");

$name = @mysql_result($result, 0, "fileName");

$size = @mysql_result($result, 0, "fileSize");

$type = @mysql_result($result, 0, "fileType");

 

header("Content-length: $size");

header("Content-type: $type");

header("Content-Disposition: attachment; filename=$name");

echo $data;

 

I can upload/download files no problem. However, I noticed problem with GIF files. All GIF files are just dark screen after downloading. All other files (PDF, JPEG) looked just fine. I compared files (before upload and after download) in HEX editor and found that the first byte on all files is set to A0 (it is added in front of all the data) and the last byte is deleted!

I have tried:

$content = addslashes($content);

 

instead of:

$content = mysql_real_escape_string($content);

with the same results

I also tried removing this line of code and in that case no file would be uploaded at all!

Any idea?

Thank you

 

Link to comment
https://forums.phpfreaks.com/topic/218064-file-as-blob-in-mysql-through-php/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.