A while back I had written a PHP/MySQL tutorial discussing how to upload an image to your server, and store the information about that uploaded image into your MySQL database. That tutorial covered really only the basics, and I knew that eventually someone would post a comment asking about some more advanced features – such as limiting the file size of uploaded images, as requested by Evaleen Tan. So this tutorial aims to expand upon the basic file upload functionality that was discussed previously and introduce various error checking features for file size, and file types, etc.

Now, let’s quickly recap where we left off in the last tutorial. We have built our basic HTML form, which requests for the users username, password, and provides an avatar upload field. This information then gets stored into a MySQL directory. So here is our final submit.php file:

 $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 "
" } else { echo "Sorry, there was a problem uploading your venue photo file."; } if ($results) { echo "New User Has Been Added!"; } mysql_close();

So the first thing we want to add to our submit.php file are a few setting options to limit what types of files we want uploaded, and how large we want them to be. We do this by an array of extensions for our file types, and a variable  that stores the maximum allowed size of any uploaded file (in bytes).

  
$allowed_filetypes = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).


Now that we have that information, we need to extract the extension of our uploaded file, and also figure out how large the uploaded file is. So to get the extension we utilize the PHP substring command which returns the portion of string specified by the start and length parameters and combine that with the string position command to find the position of the first occurrence of a substring in a string.

$ext = substr($avatar, strpos($avatar,'.'), strlen($avatar)-1); // Get the extension from the filename.

Now, let’s make use of the variables we have created so far and further amend our submit.php file with a few if/else statements:

$avatar=($_FILES['avatar']['name']); // Our uploaded file from the HTML form we created.
$allowed_filetypes = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$ext = substr($avatar, strpos($avatar,'.'), strlen($avatar)-1); // Get the extension from the filename.

// Check if the filetype is allowed, if not DIE and inform the user.
   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');

   // Now check the filesize, if it is too large then DIE and inform the user.
   if(filesize($_FILES['avatar']['name']) > $max_filesize)
      die('The file you attempted to upload is too large.');

Now let’s check if a file with a similar name already exists in our database. Furthermore while we’re at it we can include checks for our username as-well – since having duplicates of either one of those would likely cause some issues. Now we have already established a connection to our MySQL database, and if you need a refresher on this I do have a full tutorial written up about how to connect to a mysql database. Anyway let’s run a SELECT command for both the filename, and the username and check them against our database. We’ll start with the username:

$sql = "SELECT COUNT(*) num FROM users WHERE username = '" . mysql_real_escape_string($username) . "'";
$result = mysql_query($sql) or die('error');
$row = mysql_fetch_assoc($result);
if($row['num']) {
  die('This username already exists in the database.');
}

Now we do the same exact thing for the avatar’s filename:

$sql = "SELECT COUNT(*) num FROM users WHERE avatar = '" . mysql_real_escape_string($avatar) . "'";
$result = mysql_query($sql) or die('error');
$row = mysql_fetch_assoc($result);
if($row['num']) {
  die('An avatar with the same filename already exists in the database.');
}

So let’s combine everything now and finalize our new submit.php file:

// Connect To Our Database
 $dbuser = "mysql_username";
 $dbpass = "mysql_password";
 $dbhost = "localhost";
 $db = "db_name";
 mysql_connect($dbhost, $dbuser, $dbpass);
 mysql_select_db($db);

// Collect Information
$username= trim($_POST['username']);
$password= trim($_POST['password']);
$avatar=($_FILES['avatar']['name']); // Our uploaded file from the HTML form we created.

// Set Settings
$allowed_filetypes = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).

$ext = substr($avatar, strpos($avatar,'.'), strlen($avatar)-1); // Get the extension from the filename.

// Check if the filetype is allowed, if not DIE and inform the user.
   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');

// Now check the filesize, if it is too large then DIE and inform the user.
   if(filesize($_FILES['avatar']['name']) > $max_filesize)
      die('The file you attempted to upload is too large.');

// Now check for duplicate username against the database.
$sql = "SELECT COUNT(*) num FROM users WHERE username = '" . mysql_real_escape_string($username) . "'";
$result = mysql_query($sql) or die('error');
$row = mysql_fetch_assoc($result);
if($row['num']) {
  die('This username already exists in the database.');
}

// Do the same for a duplicate check against the uploaded images filename
$sql = "SELECT COUNT(*) num FROM users WHERE avatar = '" . mysql_real_escape_string($avatar) . "'";
$result = mysql_query($sql) or die('error');
$row = mysql_fetch_assoc($result);
if($row['num']) {
   die('An avatar with the same filename already exists in the database.');
}

// Specify The Target Directory for the Uploaded File
 $target = "avatars/";
 $target = $target . basename( $_FILES['avatar']['name']);

// Upload the file and run the SQL query to store all the information into the database
$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 "

} else { echo "Sorry, there was a problem uploading your venue photo file."; } if ($results) { echo "
New User Has Been Added!"; } mysql_close();

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

Join the Conversation

4 Comments

  1. there is error. Parse error: syntax error, unexpected ‘,’ in C:xampphtdocsrenzdaleuploading.php on line 25, i try to remove it and got another error again in line 25

  2. i get this error in submit.php: Parse error: syntax error, unexpected ‘;’ in C:xampphtdocsteppensubmit.php on line 26
    Line 26: if(filesize($_FILES[‘avatar’][‘name’]) > $max_filesize)

Leave a comment

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