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 { ?>

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. katalogi says:

    wow.. I dont now what it is haha

  2. Matt says:
    $fp= fopen($tmpName, ‘r’);
    $content = addslashes($content);
    fclose($fp);

    This does absolutely nothing….

  3. Tim says:

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

    $content = addslashes($tmpName);
  4. amin2u says:

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

    SpecialFile is an input name or what?

  5. wahwah says:

    SpecialFile accually is a file input name

  6. feran says:

    fine & very usefull for me.

  7. Programming Tutorials…

    I couldn’t understand some parts of this article, but it sounds interesting…

  8. Shared Hosting Resources…

    I couldn’t understand some parts of this article, but it sounds interesting…

  9. Johnny says:

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

  10. Jay says:

    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

  11. Keith says:

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

  12. Sotso F says:

    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.

  13. dionisio says:

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

  14. [...] 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 PHPCreating a Multi-File upload script in PHP. … Creating a [...]

  15. Shyam says:

    i need a good example for image uploading in database.

    and to display it… not using blob..

    thanks in advance

  16. larry says:

    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.

  17. Tou says:

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

  18. sree says:

    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

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

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

  21. mintu says:

    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

  22. vijay says:

    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 .

  23. venkat says:

    nice information its helpful to me…….

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>