Skip to main content

File Upload With PHP Script

File Upload is One of the most common and frequent activity performed by any PHP programmer. One of the most common problem I have listen from programmer is that his file upload script is working on his local machine but not on server, some files are not getting uploaded etc. All this problems arrises because of not having clear understanding of basics. In this post we will explore various cases of File upload with php programming. I will try to explain from most basic file upload to multiple file upload and progress bar in file upload script. To understand this tutorial completely basic understanding of PHP, HTML is required.
File Upload with PHP

How to perform Basic File Upload With PHP

Writing script to upload file with PHP could be one of the simplest script. First you need to create a HTML form with file input box and then you can write script in PHP to move the uploaded file at desired location. Please refer to the following steps get file upload done with PHP Script:

  1.  Create a Simple HTML Form: To get file as input from your user first you need to create a simple HTML form with file input. Following is the script with name basic.php:
    <html>
    <head>
    <title>Basic File Upload</title>
    </head>
    <body>
    <h1>Basic File Upload</h1>
    <form method="post" action="basic.php" enctype="multipart/form-data">
    <label for="inputfile">Upload File</label>
    <input type="file" id="inputfile" name="inputfile"></br>
    <input type="submit" value="Click To Upload">
    </form>
    </body>
    </html>

    The above HTML code will create a very small form with file input. Also once user will choose file and click on Upload then it will post the complete form on the same page because in <form> tag we have mentioned that action name as same as script name which is basic.php.
    Point to Remember: Please do not forget to add enctype=”multipart/form-data” in , <form> tag.
    File Upload HTML form
  2. Write PHP script to handle uploaded form: Once form with uploaded file information is receive on your basic.php then you need to write code to process the uploaded file. In PHP all uploaded file information is captured in global variable $_FILES. So using $_FILES you can check if file is uploaded or not. IF file is uploaded then you can move the file to the dedired location using move_uploaded_file function. We will explore on variable $_FILES and move_uploaded_file in later part of the tutorial.
    <?php
    if(isset($_FILES) && $_FILES['inputfile']['error'] == 0){ // To check fi user has uploaded file or not
    $destiation_dir = dirname(__FILE__) .'/'.$_FILES['inputfile']['name']; //Director where you need to put this file
    move_uploaded_file($_FILES['inputfile']['tmp_name'], $destiation_dir ); //Move the file to desired directory.
    echo 'File Uploaded'; //Send message to user that file is uploaded
    }
    else{
    echo 'No File Uploaded'; // Send message to user that no file uploaded
    }
    ?>

    Now above code will take check if user has uploaded the file or not. If uploaded then move it to the desired destination. In above script we have moved the file in the same directory where your php file basic.php is placed.

Following is the complete script to upload the file using PHP Script:
<?php
if(isset($_FILES) && $_FILES['inputfile']['error'] == 0){ // To check fi user has uploaded file or not
$destiation_dir = dirname(__FILE__) .'/'.$_FILES['inputfile']['name']; //Director where you need to put this file
move_uploaded_file($_FILES['inputfile']['tmp_name'], $destiation_dir ); //Move the file to desired directory.
echo 'File Uploaded'; //Send message to user that file is uploaded
}
else{
echo 'No File Uploaded'; // Send message to user that no file uploaded
}
?>
<html>
<head>
<title>Basic File Upload</title>
</head>
<body>
<h1>Basic File Upload</h1>
<form method="post" action="basic.php" enctype="multipart/form-data">
<label for="inputfile">Upload File</label>
<input type="file" id="inputfile" name="inputfile"></br>
<input type="submit" value="Click To Upload">
</form>
</body>
</html>

Please do not try this file on production server or live server. This script is not secure and safe to use on production. Above script is only created to explain how file upload works using php.
Question: Why the above script is not secure ?
Answer: The above script any one can upload any type of file. So if you will upload the same file on your production server or live website then hacker might upload their own php file and run through their browser and create big mess in your server.

In later part of the post we will see how to write secure File upload script in PHP.

What is $_FILES ?

$_FILES is a global variable in PHP like $_POST or $_GET. $_FILES is an associative array contains information about the uploaded file in current script from HTTP POST method.

So For above script if I did print_r($_FILES) then I got below information:

Array
(
    [inputfile] => Array
        (
            [name] => upload-file-php.jpg
            [type] => image/jpeg
            [tmp_name] => /Applications/XAMPP/xamppfiles/temp/phpcQiYhh
            [error] => 0
            [size] => 6887
        )
)

So for every  input type file (<input type=”file” name=”inputfile“/>)it creates a element in array. If you will create <input type=”file” name=”test”> then the element name will also be changed to name test. For example:

Array
(
    [test] => Array
        (
            [name] => upload-file-php.jpg
            [type] => image/jpeg
            [tmp_name] => /Applications/XAMPP/xamppfiles/temp/phpcQiYhh
            [error] => 0
            [size] => 6887
        )
)

Now for every input element like inputfile it further creates  5 sub element i.e. name, type, tmp_name, error, size. Following is the detail about the sub elements:

  1. Element “name” : Element name contains name of the file uploaded by user from HTML form. If you will upload with file name abc.txt from your browser then the file name will be abc.txt.
  2. Element “type” : Type of the file uploaded, or you can say Mime type of the file uploaded. For JPG image it will be image/jpeg for text it will be text/plain. For different type of file mime type will be different. Below are some some most comman used mine type:
    1. For JPEG file : image/jpeg
    2. For PNG file : image/png
    3. For text file : text/plain
    4. For Word file : application/msword

    Complete list of mime type is available here.

  3. Element “tmp_name” : Location where uploaded file is temporarily saved. Director to save uploaded file temporarly can be changed by changing php.ini variable upload_tmp_dir.
  4. Element “error” : Information of error if any, contains error code in numeric value. Several type of error occur during upload, for example, file exceed max file size, partial upload, no file uploaded etc. For every possible error PHP provide numeric value and have constant . Below are the complete list of error with constant name and its numeric value:
    1. UPLOAD_ERR_OK : Value 0. Mean file uploaded successfully without any error.
    2. UPLOAD_ERR_INI_SIZE : Value 1, File size exceed maximum allowed file size according to php.ini variable upload_max_filesize.
    3. UPLOAD_ERR_FORM_SIZE : Value 2, File size exceed maximum allowed file size according to MAX_FILE_SIZE variable of the form.
    4. UPLOAD_ERR_PARTIAL : Value 3, File is uploaded partial.
    5. UPLOAD_ERR_NO_FILE : Value 4, No file uploaded.
    6. UPLOAD_ERR_NO_TMP_DIR : Value 6. No temporary directory.
    7. UPLOAD_ERR_CANT_WRITE : Value 7. Can not write file to disc.
  5. Element “size” : Size of uploaded file in byte.

What is move_uploaded_file

move_uploaded_file is a php function which move the uploaded file from the temporary directory to the destination where it you want to put. Before moving the file move_uploaded_file first check whether the input file is a valid HTTP uploaded file or not.

move_uploaded_file takes 2 parameter i.e. the temporary path of upoaded file and destiantion where it need to be moved. If file moved successfully it returns true otherwise false. In our first example we have used following line:
move_uploaded_file($_FILES['inputfile']['tmp_name'], $destiation_dir )
Now let us make it better and we can write like below:

if(move_uploaded_file($_FILES['inputfile']['tmp_name'], $destiation_dir )){
echo "File Uploaded"
}
else{
echo "File Not uploaded"
}

Putting restriction or increase of file size

Every upload file form should have restriction of file size, otherwise your web user can put heavy files. You can do it by following 2 way:

    1. By changing php.ini variable: PHP.ini has variable upload_max_filesize to set the limit of file size. For example below line in php.ini will change filesize limit to 20 MB
      upload_max_filesize = 20M
      If uploaded file size will exceed then you will get error UPLOAD_ERR_INI_SIZE  or value 2 in $_FILES variable.
      Point to remember : upload_max_filesize variable value should not exceed php.ini variable post_max_size value.
    2. Hidden Input element: By Putting hidden input element with name UPLOAD_ERR_INI_SIZE in your file upload form. You can put hidden input element with value like below:

      <input type="hidden" name="MAX_FILE_SIZE" value="50000" />

Point To Remember: If you are increasing the filesize too much then do not forget to change your php maximum execution time accordingly otherwise your script execution might halt in between.

Some secure Approach of File Upload With PHP

Now we got information about how to restrict file size and how to check file type during file upload then we might put some security in our PHP script and write some better or secure PHP script to upload our file.

Now let us take example to upload jpeg image file of not exceeding 1 MB. So Please set php.ini variable upload_max_filesize. Below is the modified version of above script:

<?php
ini_set('upload_max_filesize', '1M'); //ristriction for not uploading more than 1 MB file size
if ($_SERVER['REQUEST_METHOD'] == "POST" ) {
if ($_FILES['inputfile']['error'] == UPLOAD_ERR_OK && $_FILES['inputfile']['type'] == 'image/jpeg') { //Checke if there is no error
$destiation_dir = dirname(__FILE__) . '/' . $_FILES['inputfile']['name']; //Director where you need to put this file
if (move_uploaded_file($_FILES['inputfile']['tmp_name'], $destiation_dir)) { //Move the file to desired directory.
echo 'File Uploaded'; //Send message to user that file is uploaded`
} else {
echo 'File not uploaded';
}
} else {
switch ($_FILES['inputfile']['error']) {
case UPLOAD_ERR_FORM_SIZE:
case UPLOAD_ERR_INI_SIZE:
echo 'File Size exceed';
brake;
case UPLOAD_ERR_NO_FILE:
echo 'FIle Not selected';
break;
default:
echo 'Something is wrong';
}
}
}
?>
<html>
<head>
<title>Secure File Upload</title>
</head>
<body>
<h1>Secure File Upload</h1>
<form method="post" action="secure.php" enctype="multipart/form-data">
<label for="inputfile">Upload File</label>
<input type="file" id="inputfile" name="inputfile"></br>
<input type="submit" value="Click To Upload">
</form>
</body>
</html>

Upload Multiple Files with PHP Script

You can upload multiple files with the help of using the same $_FILES and move_uploaded_file method. Following are the two way you can upload multiple file using PHP script:

  1. Using the different Input name.
  2. Using the same input name with array approach.

1. Using the different Input name:
Multiple file can be uploaded by taking multiple file input. As discussed earlier if we will create multiple  input file tag then then $_FILES will have multiple parent node. For example, for below form
<input type="file" id="profilepic" name="profilepic">
<input type="file" id="resume" name="resume">

$_FILES will provide following array:

Array
(
    [profilepic] => Array
        (
            [name] => 20141002_094257.jpg
            [type] => image/jpeg
            [tmp_name] => /Applications/XAMPP/xamppfiles/temp/phpoBWrBZ
            [error] => 0
            [size] => 2669096
        )
    [resume] => Array
        (
            [name] => 20141002_094247.jpg
            [type] => image/jpeg
            [tmp_name] => /Applications/XAMPP/xamppfiles/temp/phpjwUmVZ
            [error] => 0
            [size] => 2207657
        )
)

So you can write below script assuming that one is profile pic which is image file and other is resume which should be .doc file

<?php
if ($_SERVER['REQUEST_METHOD'] == "POST" ) {
if ($_FILES['profilepic']['error'] == UPLOAD_ERR_OK && $_FILES['profilepic']['type'] == 'image/jpeg') { //Checke if there is no error
$destiation_dir = dirname(__FILE__) . '/' . $_FILES['profilepic']['name']; //Directory where you need to put this file
if (move_uploaded_file($_FILES['profilepic']['tmp_name'], $destiation_dir)) { //Move the file to desired directory.
echo 'Profile Pic Uploaded'; //Send message to user that file is uploaded`
} else {
echo 'Profile Pic not uploaded';
}
} else {
switch ($_FILES['profilepic']['error']) {
case UPLOAD_ERR_FORM_SIZE:
case UPLOAD_ERR_INI_SIZE:
echo 'Profile Pic Size exceed';
brake;
case UPLOAD_ERR_NO_FILE:
echo 'Profile Pic Not selected';
break;
default:
echo 'Something is wrong with Profile PIC';
}
}
if ($_FILES['resume']['error'] == UPLOAD_ERR_OK && $_FILES['resume']['type'] == ' application/msword') { //Checke if there is no error
$destiation_dir = dirname(__FILE__) . '/' . $_FILES['resume']['name']; //Director where you need to put this file
if (move_uploaded_file($_FILES['resume']['tmp_name'], $destiation_dir)) { //Move the file to desired directory.
echo 'resume Uploaded'; //Send message to user that file is uploaded`
} else {
echo 'resume not uploaded';
}
} else {
switch ($_FILES['resume']['error']) {
case UPLOAD_ERR_FORM_SIZE:
case UPLOAD_ERR_INI_SIZE:
echo 'resume Size exceed';
brake;
case UPLOAD_ERR_NO_FILE:
echo 'resume Not selected';
break;
default:
echo 'Something is wrong with resume';
}
}
}
?>
<html>
<head>
<title>Multiple File Upload</title>
</head>
<body>
<h1>Multiple File Upload</h1>
<form method="post" action="multiple.php" enctype="multipart/form-data">
<label for="profilepic">Profile Pic</label>
<input type="file" id="profilepic" name="profilepic"></br>
<label for="resume">Resume</label>
<input type="file" id="resume" name="resume"></br>
<input type="submit" value="Click To Upload">
</form>
</body>
</html>

2. Using the same input name with array approach.
Like other input types we can use array approach with input type file in php. For example:
<input type="file" id="pic" name="pic[]">
<input type="file" id="pic" name="pic[]">
<input type="file" id="pic" name="pic[]">

So the $_FILES will provide data in below structure for the above HTML:

Array
(
    [pic] => Array
        (
            [name] => Array
                (
                    [0] => upload-file-php.jpg
                    [1] => variable-scope-php.jpg
                    [2] => magic-constants.jpg
                )
            [type] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                    [2] => image/jpeg
                )
            [tmp_name] => Array
                (
                    [0] => /Applications/XAMPP/xamppfiles/temp/phpML5kOy
                    [1] => /Applications/XAMPP/xamppfiles/temp/phpNZbuw7
                    [2] => /Applications/XAMPP/xamppfiles/temp/phpO8VFAk
                )
            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                    [2] => 0
                )
            [size] => Array
                (
                    [0] => 6887
                    [1] => 8036
                    [2] => 9967
                )
        )
)

Download Code used in the Post

To Read Further on File Upload with PHP Script Please refer to below URLs:
http://php.net/manual/en/features.file-upload.post-method.php
http://php.net/manual/en/features.file-upload.errors.php
http://php.net/manual/en/features.file-upload.common-pitfalls.php
http://php.net/manual/en/features.file-upload.multiple.php

Support Me by Sharing This Article

Ankur Kumar Singh

I am a PHP programmer having some knowledge about Linux. I am always interested in web development and knowledge sharing. I am full time tech evangelist part time human being. :-)

Leave a comment/Ask Question

shares