Upload Files to MySQL using PHP Tutorial

I much prefer to upload files to mysql instead of saving them directly to the file system. I can run database backups/mirrors that are much easier to manage then if files were placed on the file system.

Here are the simple scripts I use to upload files and a script to stream the file back to the browser.

MySQL Database Script:

CREATE TABLE `UploadedFiles` (
`UploadedFileID` int(11) NOT NULL auto_increment,
`name` varchar(30) default NULL,
`type` varchar(30) default NULL,
`size` int(11) default NULL,
`content` longblob,
PRIMARY KEY (`UploadedFileID`)
) TYPE=MyISAM;


Upload Script:


$value) {
$$key = $value;
}

$connect->connect_db(mydatabase)

//Insert File
if(isset($_POST['upload']) && $_FILES['SpecialFile']['size'] > 0) {
$fileName = $_FILES['SpecialFile']['name'];
$tmpName = $_FILES['SpecialFile']['tmp_name'];
$fileSize = $_FILES['SpecialFile']['size'];
$fileType = $_FILES['SpecialFile']['type'];
$fp= fopen($tmpName, 'r');
$content = addslashes($content);
fclose($fp);
}
if(!get_magic_quotes_gpc()) {
$fileName = addslashes($fileName);
}

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

$result = mysql_query($query);
if (!$result) {
dberror (mysql_error(), $_SERVER['PHP_SELF'] );
echo mysql_error();
}

//Display Confirmation
$message = urlencode("Your file has been uploaded.");
header( "Location: confirmed.php?m=$message" );
exit;
}
?>

Upload


Upload File:

To download the file I prefer to push the file down as octet stream/binary data (NOTE: To display images you would need to push out the particular mime type). That way users get the “Save” dialoge instead of the browser (especially IE) automatically trying to open with what it *thinks* should. The following codes displays the file in a drop down list for users to select and have the file streamed to their web browser.

Download File Script


connect_db(mydatabase)
$query = "SELECT * FROM UploadedFile WHERE UploadedFileID = $UploadedFileID";
$result = mysql_query( $query );
if( !$result ) {
echo mysql_error();
exit;
}

$row = mysql_fetch_array( $result );
if (!empty($row["content"]))
{
// Output the MIME header - Force as Octet Stream
// You could get this from the FileType Column
header("Content-type: application/octet-stream");
header("Content-Length: " . strlen($row['content']) );
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$row['name'].'"');
header("Content-Transfer-Encoding: binary\n");
echo $row['content'];
}

}
?>

Get File


View Files:

Tim

A .NET, PHP, Marketing Guru authority, at least I hope I am. Reach me at tboland@gmail.com

24 thoughts on “Upload Files to MySQL using PHP Tutorial


  1. $fp= fopen($tmpName, 'r');
    $content = addslashes($content);
    fclose($fp);

    This does absolutely nothing….

  2. Hi,I am using this code to my test server and it is not working. Is this code full or does it need something else? Thank you.

  3. Sorry for my english, i think that script it’s very easy to use and very cool but i need to save in the db two version of the same file.. a normal size and a thumb size.
    Do you have any idea for automatize the process with just one click?
    Thank you Tim..

  4. i need a good example for image uploading in database.

    and to display it… not using blob..

    thanks in advance

  5. well,well i have a code that relate to thesame as the one displayed here, and my question is how do i preview the image inserted to the db, what i have is use a link to donload rather than display it. And i want is to display the image on the page. Please can any one help me in doing it.

  6. hi,

    i want rss feed. that rss feed can be insert my controlpannel. that rss cotent can fecthed in to our page. it is possible

  7. This is good, But not efficient , you can use this technique when you are going to store your multiple image in database, the solution is simple store the path of multiple image , do not need the extend the fields you can store all pic path in form of serialization ,that will efficient for all application

  8. isset($_POST[‘upload’]) && $_FILES[‘SpecialFile’][‘size’] > 0

    what is $_POST[‘upload’]
    because when i am trying to print
    echo $_POST[‘upload’]; that showing nothing
    and that never pass if condition
    thanks

  9. NICE BLOG!!! Thanks for sharing useful information about FNT Softwre Solutions and being one of best Software Training institute in Bangalore we agree that this blog is very useful for the students are Searching for best software courses, I would really like to come back again right here for like wise good articles or blog posts. Thanks for sharing…PHP Training Bangalore .

Leave a Reply

Your email address will not be published. Required fields are marked *