Requirements Testing

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 16 comments.
Read more articles on php.



Related articles

16 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

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=""> <code> <em> <i> <strike> <strong> .