Uploading Images With PHP

What this tutorial will teach you:

  1. How to Upload And Handle An Image with PHP
  2. How to Decline files that aren't the correct type

Before we get started you need to create a new folder, called 'images' on your server. We will use this folder to store uploaded images.
This is all of our code for the image upload script. After this we'll walk through it step by step.
<?php

define ("MAX_SIZE","100");

function getExtension($str) {
 $i = strrpos($str,".");
 if (!$i) { return ""; }
 $l = strlen($str) - $i;
 $ext = substr($str,$i+1,$l);
 return $ext;
}

$errors=0;
if(isset($_POST['Submit'])){
 $image=$_FILES['image']['name'];
  if ($image) {
  $filename = stripslashes($_FILES['image']['name']);
  $extension = getExtension($filename);
  $extension = strtolower($extension);
  if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
   echo '<h1>Unknown extension!</h1>';
   $errors=1;
   } else {
   $size=filesize($_FILES['image']['tmp_name']);
   if ($size > MAX_SIZE*1024) {
     echo '<h1>You have exceeded the size limit!</h1>';
     $errors=1;
    }
   $image_name=time().'.'.$extension;
    $newname="images/".$image_name;
    $copied = copy($_FILES['image']['tmp_name'], $newname);
    if (!$copied) {
     echo '<h1>Copy unsuccessfull!</h1>';
     $errors=1;
   }
  }
 }
}
if(isset($_POST['Submit']) && !$errors) {
  echo "<h1>File Uploaded Successfully! Try again!</h1>";
}
?>

<form name="newad" method="post" enctype="multipart/form-data" action="">
<input type="file" name="image">
<input name="Submit" type="submit" value="Upload image">
</form>
<?php
//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","100");

Alright, let's get started by breaking down the code in chunks to make it easier to understand.

This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
This variable is used as a flag. The value is initialized with 0 (meaning no error found)
and it will be changed to 1 if an error occurs.
If the error occurs the file will not be uploaded.
$errors=0;
Checks if the form has been submitted.
if(isset($_POST['Submit'])){
This reads the name of the file the user submitted for uploading.
$image=$_FILES['image']['name'];
If the file is not empty is not empty we proceed.
if ($image) {
We get the original name of the file from the client's machine.
$filename = stripslashes($_FILES['image']['name']);
And then try to get the extension of the file in a lower case format.
$extension = getExtension($filename);
$extension = strtolower($extension);
If it is not a known extension, we will suppose it is an error and will not upload the file,
otherwise we will do more tests.
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
If the extension doesn't match one of our requirements we print an error message.
echo '<h1>Unknown extension!</h1>';
$errors=1;
} else {
Now we get the size of the image in bytes.
$_FILES['image']['tmp_name'] is the temporary filename of the file.
$size=filesize($_FILES['image']['tmp_name']);
We compare the size with the maxim size we defined and print error if bigger.
if ($size > MAX_SIZE*1024) {
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
We will give the file a unique name, for example the time in UNIX time format.
$image_name=time().'.'.$extension;
The new name will contain the full path where the file will be stored, the images folder you created earlier.
$newname="images/".$image_name;
We verify if the image has been uploaded, otherwise we print out an error.
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied) {
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1; }}}}
If no errors registered, print the success message.
if(isset($_POST['Submit']) && !$errors) {
echo "<h1>File Uploaded Successfully! Try again!</h1>";
}
?>
Next comes the form, you must set the encrypt to "multipart/frm-data" and use an input type "file".
<form name="newad" method="post"
enctype="multipart/form-data" action="">
This is the rest of the form.
<table>
<tr><td><input type="file"
name="image"></td></tr>
<tr><td><input name="Submit" type="submit"
value="Upload image"></td></tr>
</table>
</form>
So now we've got a fully functioning image uploader script. You can change the naming mechanism to anything you like. In the case of allowing users to upload photos of themselves, it may be a good idea to us the users name and a random number as the photos name. But there are also a lot of other ways to do it as well. Experiment a little bit and see what you like.