Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

PHP File Upload

Reading this article you can learn to create and understand how the file upload works in PHP language. You will see some good resources to use in this system.

Handling File Uploads in PHP

As most of the people tend to relate the HTTP with web pages, actually it facilitates the transfer of any kind of files such as MS Office documents, PDFs, executables, video files, zip files and a wide variety of other files. Although historically FTP has been the standard way of uploading files to the server, these days, most of the files are uploaded via a web based interface.

PHP File Upload/Resource Directives

PHP comes with various configuration directives to fine tune PHP file upload capabilities. These directives are responsible for determining that whether the file-upload support of PHP is enabled or not, the maximum file size allowed to upload, the maximum allowable script memory allocation, and many more important resource benchmarks. Some important directives are introduced below:

file_uploads= On / Off

Scope: PHP_INI_SYSTEM; Default value: 1

This directive determines that PHP scripts on the server can allow the file uploads or not.


Scope: PHP_INI_ALL; Default value: 8M

This directive sets a maximum allowable amount of memory for a script to execute. This memory is in megabytes and M must be present after the integer value for this setting to work properly. This prevents the scripts to acquire too much memory which can crash the server in certain situations.

max_execution_time = integer

Scope: PHP_INI_ALL; Default value: 30

This directive sets the maximum time to execute a PHP script before reporting a fatal error. This time will be in seconds.

upload_max_filesize = integerM

Scope: PHP_INI_SYSTEM; Default value: 2M

This directive is responsible for setting the maximum size of an uploaded file in megabytes. M must follow the integer value same as it follows in memory_limit directive.

upload_tmp_dir = string

Scope: PHP_INI_SYSTEM; Default value: NULL

This directive defines a location where the uploaded file will be placed temporarily until they are moved to their final location. For example, suppose user want to store uploaded files temporarily in the /tmp/php_uploads/ directory , then he would use the following:

upload_tmp_dir = "/tmp/php_uploads/"

The owner of the server process must have the write access to this directory. It is very important that Apache process owner should be made either the owner of the temporary upload directory or a member of the group who owns the directory.

post_max_size = integerM

Scope: PHP_INI_SYSTEM; Default value: 8M

This directive determines the maximum allowable size of information can be accepted via the POST method. This directive setting should be larger than upload_max_filesize to accommodate any other form field that may be passed in addition to the uploaded file. M must follow the integer value like memory_limit and upload_max_filesize.

The $_FILES Array

The $_FILES superglobal is the only two-dimensional array of the predefined EGCPFS (get, cookie, put, environment, files, server) superglobal arrays. It stores various information related to a file uploaded to a server by a PHP script. The items of this array are defined below:

  • $_FILES['userfile']['error']: This array value represent the outcome of a upload attempt. It return five values, one represents a successful attempt, other four returns specific errors arises from the attempt.
  • $_FILES['userfile']['name']: This variable stores the original name and extension of the file, declared on client machine. Suppose, you upload a file alok.jpg via the form, the value alok.jpg will be assigned to this variable.
  • $_FILES['userfile']['size']: The size of the file uploaded from the client machine is assigned to this variable in bytes.
  • $_FILES['userfile']['tmp_name']: This variable stores the temporary name assigned to the uploaded file while stored in the temporary storage (specified by the PHP directive upload_tmp_dir).
  • $_FILES['userfile']['type']: This variable store the MIME type of the file uploaded from the client machine. Therefore, if a file named location.pdf was uploaded, the value assigned to this variable would be application/pdf. If a image file like .png was uploaded the, value image/png would be assigned.
  • File Upload Functions of PHP

    PHP provides two more functions, is_uploaded_file() and move_uploaded_file(), specifically intended to make file uploading process easier. This section introduces both of these functions below:


    This function determines that whether a file by the input parameter filename is uploaded via the POST method or not. The function prototype is declared as follows:

    boolean is_uploaded_file(string filename)

    This function has a very important role to stop an attacker from manipulating those files which should not be interacted via the script. For example, if an attacker wants to access a file /etc/passwd rather than the publically available files such as javanotes. So he types /etc/passwd directly into the form’s file-upload field instead rather than navigate to the javanotes file.

    Now this is an uploadmanager.php script:

    Listing 1: uploadmanager.php code


    Because of this poorly written script, /etc/passwd file will be copied to a publically accessible file. To prevent this, use is_uploaded_file()function to ensure that file denoted by the form field, in our case javanotes, is the file , uploaded via the form. The improved and revised code of the same uploadmanager.php script is given below:

    Listing 2: Updated uploadmanager.php

    if (is_uploaded_file($_FILES['javanotes']['tmp_name'])) {
    } else {
    echo "<p>Potential script abuse attempt detected.</p>";

    In this script, the function is_upload_file() checks that if the file denoted by $_FILES[‘javanotes’][‘tmp_name’] has been uploaded successfully then, it is copied to the desired destination. Otherwise, an error message will be popped up.


    This function is used to move an uploaded file from temporary to a permanent location. The prototype of this function is as follows:

    boolean move_uploaded_file(string filename, string destination)

    This function checks that the file was in fact uploaded via PHP’s HTTP POST upload mechanism. A FALSE value will be returned , if the file was not uploaded.

    Using this function is simple. In a scenario, where you want to move the uploaded Java notes file to a directory /www/htdocs/javanotes/, while preserving the filename as specified on the client:


    You can rename the file to anything when it is moved but you have to reference the temporary name of the file properly within the first parameter.

    Upload Error Messages

    It is not possible to achieve success every time in file uploading process. Sometime an error can cause failure of file uploading. Thankfully, sufficient information is provided by PHP for determining the reason for the error in $_FILES['userfile']['error']:

    • UPLOAD_ERR_OK: When file is uploaded successfully, a 0 value will be returned.
    • UPLOAD_ERR_INI_SIZE: When the size of file will be greater than the maximum size defined in upload_max_filesize directive, a value of 1 will be returned.
    • UPLOAD_ERR_FORM_SIZE: If user tries to upload a file of size greater than the value of max_file_size, which can be embedded into the HTML form, then a value of 2 will be returned.
    • UPLOAD_ERR_PARTIAL: When a file is not completely uploaded, value of 3 will be returned.
    • UPLOAD_ERR_NO_FILE: If a form is submitted without specifying a file to upload then, value 4 will be returned.

    A Simple Example

    This is simple example of file uploading. In this scenario, A professor invites his class students to post class notes to his website so that everybody can access them. Each file should be renamed to the last name of the student. And, only PDF file can be uploaded.

    Listing 3: A Simple File-Upload Example

    <form action="uploadmanager.php" enctype="multipart/form-data" method="post">
    Last Name:<br /> <input type="text" name="name" value="" /><br />
    Class Notes:<br /> <input type="file" name="classnotes" value="" /><br />
    <p><input type="submit" name="submit" value="Submit Notes" /></p>
    /* Set a constant */
    define ("FILEREPOSITORY","/home/www/htdocs/class/classnotes/");
    /* Make sure that the file was POSTed. */
    if (is_uploaded_file($_FILES['classnotes']['tmp_name'])) {
    /* Was the file a PDF? */
    if ($_FILES['classnotes']['type'] != "application/pdf") {
    echo "<p>Class notes must be uploaded in PDF format.</p>";
    } else {
    /* move uploaded file to final destination. */
    $name = $_POST['name'];
    $result = move_uploaded_file($_FILES['classnotes']['tmp_name'], 
    if ($result == 1) echo "<p>File successfully uploaded.</p>";
    else echo "<p>There was a problem uploading the file.</p>";
    } #endIF
    } #endIF


    Transferring the files removes many problems posed by firewalls and FTP server and clients. The ability to easily manipulate and publish non-traditional data is also enhanced. You just learned how easy it is to add such capabilities to your PHP application.

    Hope you liked the article, please let me know if you have any question and see you next time.

Have total 6+ years of experience in developing enterprise applications using DOT.NET 3.5 and 4.0(C#, VB.NET, ADO.NET, ASP.NET),java, JQuery, JSON, LINQ,WCF, MVC3, MVC4, Silverlight, SQL Server, mobile applications and Oracle etc ...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login