creating an image upload form with PHP

Building a page in Dreamweaver which can be used to upload images to an online server.

Dreamweaver Set Permissions option

Before working with any code, you will need to make sure that you have a folder on your remote server that can receive files that we will send to it. So, create a folder called ‘uploads’, right click on it and select ‘Set Permissions…’ (see the image on the left) then make sure that all the boxes are ticked. This will enable public users (i.e. people viewing the page through a web browser) to have complete access to that folder.

777 Rewrite

Now, change your view to split view and using the ‘Forms’ tab in Dreamweaver, insert a form onto your page. Within that form, add a File field with the id of ‘imgFile’ and then add a Submit button. (see image here)

When this form has been submitted, we want the page to return to itself, so amend the ‘action’ attribute in the html of your form to the following:

action="<? echo($_SERVER['PHP_SELF']); ?>"

Form action

Also, make sure the enctype attribute of the form is set to multipart/form-data.

We’re now going to set up some code that will get information about the file selected for upload. We want to find out the name, temporary name (because the file is initially stored in a temporary location on the server), size and file type. So, at the top of the page, add the following:

<?
//BEGIN FORM SUBMISSION CODE
$imgFileName=$_FILES['imgFile']['name'];
$imgFileTmp=$_FILES['imgFile']['tmp_name'];
$imgFileSize=$_FILES['imgFile']['size'];
$imgFileType=$_FILES['imgFile']['type'];
//END FORM SUBMISSION CODE
?>

This creates 4 variables and assigns them values directly from the ‘imgFile’ form object that we creates earlier. You can see that the first set of square brackets identify that object and the second set determine the data we’re looking for.

Note: The comments will help us to identify this code block later.

To actually see this information on the page, you can add this somewhere in your html body;

<? echo($imgFileName."<br />");?>
<? echo($imgFileTmp."<br />");?>
<? echo($imgFileSize."<br />");?>
<? echo($imgFileType."<br />");?>

If you then save this page and upload it, you can use it to select an image on your computer to ‘upload’. When you press ‘Submit’, the page will refresh itself and display information about the file you have selected. (This information does not need to be displayed for the form to work, but it’s helpful to see it while you’re testing the form).

Information about the uploaded file

At this point, the file itself has not actually been uploaded to the server. For that to happen, it has to be copied from it’s temporary location to the directory we created at the start. So, go back to your PHP code and add this to your form submission code.

$filePath="uploads/".$imgFileName;
move_uploaded_file($imgFileTmp,$filePath);

When you now look at the page and select an image to upload it’ll actually upload to your online directory.

A newly uploaded file

Using the $filePath variable, we can also display the uploaded image after it’s been uploaded. Underneath your upload form in your html, add:

<img src="<? echo($filePath) ?>">

Camel picture uploaded

When you upload the page this time and select a new image to upload, you will get the image displayed on the page after you hit ‘Submit’.

Fine and dandy!

Or is it(?)

The problem with the upload form as it stands, is that anything can be uploaded to the server. To ensure that users aren’t abusing the file upload, we’ll need to check the file adheres to certain criteria to make sure it’s acceptable. We can check the file size, the file type, whether it already exists and if the upload was actually successful. A few chunks of code can be added to solve these very problems.

File size..
Go to your code and at the top, create the following variables:

$maxFileSize=20000;
$message="";

This will be used to determine how big a file you will allow people to upload (the number is in bytes) and will also create a variable called ‘message’ which we’ll use shortly. Then, on a line before the move_uploaded_file() function, add the following code:

if($imgFileSize > $maxFileSize){
$message="Sorry, your file exceeds the $maxFileSize bytes limit<br />";
}

File type..
Directly after the file size ‘if’ statement that you just added, continue with:
if($imgFileType=="image/jpeg" || $imgFileType=="image/gif"){
//file ok
}else{
$message.="File needs to be gif or jpeg<br />";
}

Whether it already exists..
Then add:

if(file_exists($filePath)){
$message.="File name exists<br />";
}

Finally, beneath those if statements, add this if statement which will mean that your error messages don’t get displayed prematurely.

if(!isset($imgFileTmp)) {
$message="";
}

If you then add,

<p><? echo($message."<br />");?></p>

near where you have your current ‘echo’ statements, and then save the page, you can check that these statements all work by uploading files that are too big, are of the wrong type (not a gif or jpeg) or have already been uploaded. You will see an error message but the files will actually still be uploaded because we’ve not yet written in a function to stop them from doing so.

Error messages

So, the final piece of PHP we’ll add to this page will stop the upload from taking place if anything is wrong. At the top of the code, there is a variable called $message which starts off empty. This variable gets a value assigned to it if any of the various ‘errors’ occur, so we can use this to work out whether the upload should be allowed or not. If it’s empty by the end of the code, then we can assume that everything is hunky dory and continue as normal. So we need to enclose the ‘move_uploaded_file’ function within an if statement in one that checks $message:

if($message==""){
move_uploaded_file($imgFileTmp,$filePath);
}

This complete code will now only upload images that are less than your specified file size, either a gif or a jpeg and haven’t been uploaded before (based on the file name)!

As a final note, this script wont allow you to ever upload an image which has the same name as an existing image. If you want to avoid this and give each new uploaded image a unique name, add this just below where you have the $filepath variable.

//Uncomment the two variable lines if you want to implement this code.
//As an alternative, you could name each file with a unique name.
//The time() function returns the number of seconds since 1970!
//Since this will always be a unique number, you can create
//unique file names.
//First you would need to get the extension from the file. explode()
//does this:

#$fileparts=explode(".",$imgfilename);

//The explode function breaks up strings according to the separator
//specified in the first argument. The results are put into an array,
//or list.
//To put it all together, you can use:

#$filepath="uploads/".time().".".$fileparts[1];

//The [1] in $fileparts specifies the element of the array.

The comments should be self explanatory.

Stuff.