Home > Tutorials > PHP Tutorials > File Upload via PHP/MySQL

File Upload via PHP/MySQL

As per the request of Spaculus I have decided to put together a tutorial discussing how to upload an image to your server, and store the information about that uploaded image into your MySQL database. This is a function that can often come in handy when developing a user membership system with avatar support, or a venue/event listing that displays an image for a venue/event. For this tutorial we are going to assume that we are creating a simple user membership system with avatar support. Upon registration the user will be asked to select an avatar they wish to use for themselves.

Please note that the user registration process shown here does not include any error checking, nor does it check the database if the same username exists. This is merely done as a demonstration and to better show how you can utilize the various functions outlined within this tutorial.

We’ll start with setting up our database. You can either use phpMyAdmin to manually create all of your rows, or simply execute the following SQL:

CREATE TABLE `users` (
`id` int(6) NOT NULL auto_increment,
`username` varchar(50) NOT NULL default '',
`password` varchar(50) NOT NULL default '',
`avatar` text NOT NULL default '',
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) TYPE=MyISAM AUTO_INCREMENT=1 ;

Now that we have our database setup, let’s create a simple registration form:

<form enctype="multipart/form-data" id="signup" action="submit.php" method="post" name="signup">
Username: <input id="name" name="name" type="text" size="25">
Password: <input id="name" name="name" type="password" size="25">
Avatar: <input id="photo" name="photo" type="file" size="25" value="" maxlength="255">
<input type="submit" name="submitButtonName" value="Add">
</form>

Take note that I have set the form’s encoding type to multipart/form-data – without this the server simply will not process the image that we’re trying to upload.  I’m submitting my form to a file called submit.php – but you can obviously call yours whatever you want – just remember to change the filename in the code above.

Now let’s start working on our submit.php file. First thing we’ll want to do here is connect to our database. I won’t go into detail on this part here – however I do have a full tutorial written up about how to connect to a mysql database, feel free to give that a read through if you need any help. Once we’ve connected to the database we’ll use PHP’s $_POST array to save all the information submitted via our form into variables, and set the target folder where we wish to store all our uploaded files. Note that while all the text fields will be submitted via the $_POST array, the avatar gets submitted via the $_FILES array.  The $target variable sets the relative folder where the users files will be submitted; make sure you create this folder prior to running the script the first time or you will encounter an error.

<?php
 $dbuser = "mysql_username";
 $dbpass = "mysql_password";
 $dbhost = "localhost";
 $db = "db_name";
 mysql_connect($dbhost, $dbuser, $dbpass);
 mysql_select_db($db);
 $username= trim($_POST['username']);
 $password= trim($_POST['password']);
 $avatar=($_FILES['avatar']['name']);
 $target = "avatars/";
 $target = $target . basename( $_FILES['avatar']['name']);
 mysql_close();
 ?>

Now that we have all our variables setup we can start with the first main part – saving all of this information into our database. For this we will use the following query:

mysql_query("INSERT INTO `users` VALUES ('','$username', '$password', '$avatar')");

Next we take the uploaded file and move it into our target directory. If the file gets uploaded correctly – we’ll let the user know. Otherwise we need to degrade gracefully and let the user know there was an error.

 if(move_uploaded_file($_FILES['avatar']['tmp_name'], $target))
{
 echo "The image ". basename( $_FILES['uploadedfile']['name']). " has been uploaded.";
}
 else
{
 echo "Sorry, there was a problem uploading your venue photo file.";
}

Finally we need to tie everything together and make sure our MySQL query from before has executed without any errors. To do this we’ll set the whole query into a variable, then test to see if that variable is null or not. If it’s not null – we  know that our query has successfully been executed. The final code for submit.php looks like this:

 $dbuser = "mysql_username";
 $dbpass = "mysql_password";
 $dbhost = "localhost";
 $db = "db_name";
 mysql_connect($dbhost, $dbuser, $dbpass);
 mysql_select_db($db);
 $username= trim($_POST['username']);
 $password= trim($_POST['password']);
 $avatar=($_FILES['avatar']['name']);
 $target = "avatars/";
 $target = $target . basename( $_FILES['avatar']['name']);
$results = mysql_query("INSERT INTO `users` VALUES ('','$username', '$password', '$avatar')");
if(move_uploaded_file($_FILES['avatar']['tmp_name'], $target))
 {
  echo "The image ". basename( $_FILES['uploadedfile']['name']). " has been uploaded.";
  echo "<center><img alt="" src="http://rapidpurple.com/blog/tutorials/php-tutorials/file-upload-via-phpmysql/" /></center>"
 } 
else 
 { 
echo "Sorry, there was a problem uploading your venue photo file."; 
 } 
if ($results) { 
echo "New User Has Been Added!"; 
} 
mysql_close();

About Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Check Also

5 Must Have WordPress Optimization Plugins For A Fast Loading Website

Having a fast loading website is essential these days. First off, users are impatient. If ...

  • BoardTomSailor

    Thanks a ton bro ..

    I was looking for some decent tutorials on PHP .. I am quite new .. with zero programming experience ..

    Kindly put up references to some other sites which can help me with PHP just like this ..

  • Captain Newgate

    Thank god, you wrote about the submit.php,,,, else I would be lost .. a couple of site I checked earlier, didn’t mention submit.php they just gave only the schematics / pseudo code. Thank you again

  • KumarieeMeena

    Yeah, good one bro .. way to go .. I am still lost .. Ha Ha

    • Metalp3n

      Have any questions? Feel free to ask away.

  • anafa david mudi

    Guy, you saved my day, with this it has helped me greatly on my PHP-Mysql learning curve. May God bless you…

    • Metalp3n

      If you need any help, feel free to ask.

      • Evaleen Tan

        Please reply to my above comment, thank you!

  • Evaleen Tan

    U there

  • Evaleen Tan

    I need help here:
    myPicasa.html contains a form where users can upload their photos in the form of an image file.

    Poster

    The page doUploadPic.php saves a copy of the …

  • Evaleen Tan

    The page doUploadPic.php saves a copy of the uploaded picture in a folder named “picDirectory” under htdocs directory. This page only accepts images that are less than 5000 bytes in size. Fill in the blanks for doUploadPic.php.

    //check if the file size is less than 5000 bytes
    if ( ___________________________________) {
    //set target folder to store the uploaded image file
    $targetDir = “______________________________”;
    //get the original filename of the uploaded image file
    $imageFile = basename (_________________________);
    //append the folder name to the original filename
    $targetDir = ________________________________;
    //move the uploaded file to the intended location
    if (_______________________________________________{
    echo “The file “. ________________. ” has been uploaded”;
    } else{
    echo “There was an error uploading the file, please try again!”;
    }
    }

  • Gerald

    This tutorial is outdated and should not be used anymore. The mysql_* functions are becoming deprecated and will be removed from future versions of PHP.

    • Metalp3n

      Becoming being the key word. Fact is that the majority of hosting companies won’t be past PHP 5.4 for a while now – they generally maintain older versions for quiet a while to maintain support for older scripts and applications.

      With that said I am working on a new version of these tutorials utilizing the MySQLi extension.