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.

$formaction = $_SERVER['PHP_SELF']; //the URL the form should send users to on submit
$allowedfiletypes = array('csv'); //a comma separated list of allowed extensions
$uploadfolder = './'; //the folder where the uploaded file should be moved to
$uploadfilename = 'data.csv'; //the filename that the uploaded file should be renamed to

//check to see if the form has been submitted
if (array_key_exists('action',$_POST) && is_string($_POST['action']) && (strip_tags($_POST['action']) == 'upload')) { //the form has been submitted
    echo '<p>Uploading file... ';
    if (empty($_FILES['uploadfile']['name'])) {
        echo '<strong>Error: File not uploaded!</strong></p>';
    } else {
        $fileext = strtolower(substr($_FILES['uploadfile']['name'],strrpos($_FILES['uploadfile']['name'],'.')+1));
        if (!in_array($fileext,$allowedfiletypes)) {
        	echo '<strong>Error: Invalid file extension!</strong></p>';
        } else { //a file of the correct type was uploaded
            $fulluploadfilename = $uploadfolder.$uploadfilename;
            if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $fulluploadfilename)) {
                echo 'Your file has been uploaded succesfully:<br>'.$fulluploadfilename.'</p>';
            } else {
            	echo '<strong>Error: Could not save file:<br>'.$fulluploadfilename.'</strong></p>';

echo '<form action="'.$formaction.'" method="post" enctype="multipart/form-data">';
echo '<p>Your CSV file:<br><input type="file" name="uploadfile"></p>';
echo '<p><input type="submit" class="button" value="Upload File"></p>';
echo '<input type="hidden" name="action" value="upload">';
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.



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 of use.