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:

'holds db constructor
include("{$_SERVER['DOCUMENT_ROOT']}/phplibrary/dbconnect.php");
###################
//Consume Post Vars
###################
if (!empty($_POST['upload']))
{
//Loop thru Post Array
foreach($_POST as $key => $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 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

//holds db constructor
include("{$_SERVER['DOCUMENT_ROOT']}/phplibrary/dbconnect.php");

if (!empty($_POST['GetFile']))
{
$UploadedFileID = $_POST["UploadedFileID"];
$connect->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'];
}

}
?>


$connect->connect_db(mydatabase)
$result = mysql_query(“SELECT UploadedFileID, name FROM UploadedFiles”);
if ($myrow = mysql_fetch_array($result)) {
do { ?>

Written by Tim on July 20th, 2006 with 24 comments.
Read more articles on php.

Related articles

24 comments

Read the comments left by other users below, or:

Get your own gravatar by visiting gravatar.com katalogi
#1. April 17th, 2007, at 9:35 AM.

wow.. I dont now what it is haha

Get your own gravatar by visiting gravatar.com Matt
#2. April 30th, 2007, at 9:38 PM.

$fp= fopen($tmpName, ‘r’);
$content = addslashes($content);
fclose($fp);

This does absolutely nothing….

Get your own gravatar by visiting gravatar.com Tim
#3. April 30th, 2007, at 11:33 PM.

Matt,
Oops, wrong variable in the addslashes – should be

$content = addslashes($tmpName);

Get your own gravatar by visiting gravatar.com amin2u
#4. May 5th, 2007, at 1:51 AM.

$_FILES['SpecialFile']['name'];

SpecialFile is an input name or what?

Get your own gravatar by visiting gravatar.com wahwah
#5. July 11th, 2007, at 7:21 AM.

SpecialFile accually is a file input name

Get your own gravatar by visiting gravatar.com feran
#6. July 13th, 2007, at 12:30 PM.

fine & very usefull for me.

Trackback Mention from Tutorials.goodfind.org
#7. August 17th, 2007, at 8:09 AM.

Programming Tutorials: Programming Tutorials... I couldn't understand some parts of this article, but it sounds interesting...

Trackback Mention from Aidinc.org
#8. September 13th, 2007, at 4:08 PM.

Shared Hosting Resources: Shared Hosting Resources... I couldn't understand some parts of this article, but it sounds interesting...

Get your own gravatar by visiting gravatar.com ss@bb.com
#9. December 13th, 2007, at 1:55 PM.

v

Get your own gravatar by visiting gravatar.com Johnny
#10. December 13th, 2007, at 1:56 PM.

I do not understand what is the “r” for?
any ideas?

Get your own gravatar by visiting gravatar.com Jay
#11. January 18th, 2008, at 4:29 PM.

The ‘r’ is to tell php to read the file. Check this link out for somemore details.

http://us.php.net/manual/en/function.fopen.php

Get your own gravatar by visiting gravatar.com Keith
#12. March 30th, 2008, at 1:44 AM.

Great tutorial but how do you use mysql to display the image after.
Just the image not the rest of the info???

Get your own gravatar by visiting gravatar.com Sotso F
#13. March 30th, 2008, at 3:25 AM.

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.

Get your own gravatar by visiting gravatar.com dionisio
#14. April 5th, 2008, at 5:24 PM.

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..

Trackback Mention from Madalynn.unrestrictednews.com
#15. April 27th, 2008, at 12:39 AM.

php file upload script: with PHP TutorialGreat tutorial on uploading files directly to mysql using PHP. Scripts included.http://www.techtoolblog.com/archives/upload-files-to-mysql-using-php-tutorialCreating a Multi-File Upload Script in ...

Get your own gravatar by visiting gravatar.com Shyam
#16. July 22nd, 2008, at 8:06 PM.

i need a good example for image uploading in database.

and to display it… not using blob..

thanks in advance

Get your own gravatar by visiting gravatar.com larry
#17. September 30th, 2008, at 10:58 AM.

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.

Get your own gravatar by visiting gravatar.com Tou
#18. December 12th, 2008, at 10:28 AM.

Could you please advice about this code? how much is the file size that it can be support?

Get your own gravatar by visiting gravatar.com sree
#19. March 25th, 2010, at 9:42 AM.

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

Get your own gravatar by visiting gravatar.com Abdullah raza lakhan
#20. November 23rd, 2012, at 2:17 PM.

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

Get your own gravatar by visiting gravatar.com Mudasir Nazir
#21. February 20th, 2013, at 3:52 PM.

I compared you script with this script that is available here
http://www.computersneaker.com/php-file-upload-script/
And i have found lot of problems, Can you please compare the code spinets?

Get your own gravatar by visiting gravatar.com mintu
#22. February 20th, 2013, at 6:46 PM.

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

Get your own gravatar by visiting gravatar.com vijay
#23. March 19th, 2013, at 7:15 AM.

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 .

Get your own gravatar by visiting gravatar.com venkat
#24. September 1st, 2013, at 9:48 AM.

nice information its helpful to me…….

Leave your comment...

If you want to leave your comment on this article, simply fill out the next form:




You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> .