Easy way to upload with PHP and HTML

Categorized under: Web Development

In this tutorial I will show you how to upload a file on your server using PHP script and HTML form.

The basics

HTML form

In order to be able to upload a file, make sure your form has:
- enctype=”multipart/form-data”
- method=”post”

<form enctype="multipart/form-data" action="upload.php" method="post">
	Please choose a file:
	<input type="file" name="uploadedFile" />
	<input type="submit" name="save" value="Upload" />
</form>

This form will send the post to the file upload.php

PHP script

Now let’s discuss about upload.php.
First thing is to verify if the form was submited correctly. For this, is only necessary to have the following condition:

if($_POST['save']){
   // the rest of the script goes here
}

Keep in mind that the uploaded file(s) can be accessed with the $_FILES variable.

So $_FILES['uploadedFile'] will be an array of info about the uploaded file. Like it follows:
- name: name of the original file
- type: MIME type of the file
- tmp_name: temporary name on the server
- error: error number, if any error occured while uploading
- size: size of the file, in bytes.
Next, we will use this info to check, name and upload new file. Next it’s time to check if any error occurred while uploading the file.

if($_FILES['uploadedFile']['error']!==0){
	$error = 'File could not be uploaded. Please try again.';
}

In order to make sure the file was properly uploaded by the user and a malicious user hasn’t tried to trick the script, we will use is_uploaded_file(tmp_name) as follows

if(!$error){
	if(!@is_uploaded_file($_FILES['uploadedFile']['tmp_name'])){
		$error = 'The process cannot continue. Please contact webmaster.';
		// Malicious user?
	}
}

Now is time to properly upload the file on your server. For this we will use move_uploaded_file(tmp_name, new_name)

if(!$error){
	$uploadDirectory = 'media/upload/';
	$uploadName = $_FILES['uploadedFile']['name'];
	// uploadDirectory must be set as absolute path or as relative path to upload.php

	if(!@move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $uploadDirectory.$uploadName)){
		$error = 'There was a problem storing the file. Please contact webmaster.';
		// Permission denied to write into folder or hardware issues?
	}
}

If no error occured, we should inform the user and redirect him to a new page.

if(!$error){
	// all done, inform user and redirect
	$continueTo = 'fileUploaded.php';
	header("Location: $continueTo");
}

Here is the whole content for upload.php

if($_POST['save']){
	$error = NULL;

	if($_FILES['uploadedFile']['error']!==0){
		$error = 'File could not be uploaded. Please try again.';
	}

	if(!$error){
		if(!@is_uploaded_file($_FILES['uploadedFile']['tmp_name'])){
			$error = 'The process cannot continue. Please contact webmaster.';
			// Malicious user?
		}
	}

	if(!$error){
		$uploadDirectory = 'media/upload/';
		$uploadName = $_FILES['uploadedFile']['name'];
		// uploadDirectory must be set as absolute path or as relative path to upload.php

		if(!@move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $uploadDirectory.$uploadName)){
			$error = 'There was a problem storing the file. Please contact webmaster.';
			// Permission denied to write into folder or hardware issues?
		}
	}

	if(!$error){
		// all done, inform user and redirect
		$continueTo = 'fileUploaded.php';
		header("Location: $continueTo");
	}
}

if($error) echo $error;

Advanced

Before allowing users to upload files on your server, you should know that not all the people have good intentions and you should protect your server from unwanted files.

1. Restrict file extensions: You don’t want a user be able to upload a php file on your server. That’s why a good idea to restrict uploading to a certain file extensions. Here is how we do it:

if(!$error){
	$allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');
	$fileExtension = array_pop(explode('.', $_FILES['uploadedFile']['name']));
	if(!in_array($fileExtension, $allowedExtensions)){
		$error = 'You can upload only images. Please try again.';
	}
}

2. Restrict file types: You can check the mime-type of the uploaded type and allow certain types to be uploaded.

if(!$error){
	$allowedMime = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif');
	if(!in_array($_FILES['uploadedFile']['type'], $allowedMime)){
		$error = 'You can upload only images. Please try again.';
	}
}

3. Check filesize: There is a initial maximum size for files uploaded. You can check it with

echo ini_get('post_max_size');

But if your space is limited, then you should consider limiting filesize to a resonable value. The following code rejects all the files that is bigger than a given value

if(!$error){
	$maximumSize = pow(2, 20);
	// 1 MB
	if($_FILES['uploadedFile']['size'] > $maximumSize){
		$error = 'Your file is too big. Please try again.';
	}
}

Download here the files.

Hope you enjoyed the reading. Any other ideas on how to protect your upload script?

Comments

  1. Nice to read your blog


    Danielle
    January 15th, 2012
  2. I was looking after an upload script, but your tutorial is way more better. Thanks!


    Cris
    January 29th, 2012