Simple PHP Upload Form

This tested and working PHP form allows your users to upload a CSV file.

I picked CSV files just to pick something for the sake of this example, but a quick change to the array in line 2 will allow for whatever type of file you want uploaded.

1.   $formaction = $_SERVER['PHP_SELF']; //the URL the form should send users to on submit
2.   $allowedfiletypes = array('csv'); //a comma separated list of allowed extensions
3.   $uploadfolder = './'; //the folder where the uploaded file should be moved to
4.   $uploadfilename = 'data.csv'; //the filename that the uploaded file should be renamed to
6.   //check to see if the form has been submitted
7.   if (array_key_exists('action',$_POST) && is_string($_POST['action']) && (strip_tags($_POST['action']) == 'upload')) { //the form has been submitted
8.   	echo '<p>Uploading file... ';
9.   	if (empty($_FILES['uploadfile']['name'])) {
10.  		echo '<strong>Error: File not uploaded!</strong></p>';
11.  	} else {
12.  		$fileext = strtolower(substr($_FILES['uploadfile']['name'],strrpos($_FILES['uploadfile']['name'],'.')+1));
13.  		if (!in_array($fileext,$allowedfiletypes)) {
14.  			echo '<strong>Error: Invalid file extension!</strong></p>';
15.  		} else { //a file of the correct type was uploaded
16.  			$fulluploadfilename = $uploadfolder.$uploadfilename;
17.  			if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $fulluploadfilename)) {
18.  				echo 'Your file has been uploaded succesfully:<br>'.$fulluploadfilename.'</p>';
19.  			} else {
20.  				echo '<strong>Error: Could not save file:<br>'.$fulluploadfilename.'</strong></p>';
21.  			}
22.  		}
23.  	}
24.  }
26.  echo '<form action="'.$formaction.'" method="post" enctype="multipart/form-data">';
27.  echo '<p>Your CSV file:<br><input type="file" name="uploadfile"></p>';
28.  echo '<p><input type="submit" class="button" value="Upload File"></p>';
29.  echo '<input type="hidden" name="action" value="upload">';
30.  echo '</form>';

Make sure that your upload directory is writeable. A common stumbling block is not setting permissions correctly there.

Also, be sure that you don't forget to include the enctype="multipart/form-data" in the <form> tag. The file upload won't work without that being present.

If you're uploading an image instead, check out this PHP form to upload an image. It also creates a thumbnail of the uploaded image.

Leave a Comment

Name and email are required. Your email will not be published.

This post was published on December 23rd, 2015 by Robert James Reese in PHP. Before using any of the code or other content in this post, you must read and agree to our Terms & Conditions.