File Uploading in PHP

Hello Readers!
File Uploading is now a requirement of almost every web application. Uploading means tranferring a file from user computer (Client) to the server. While uploading a file, many aspects like file size,file type etc should be considered to make it a secure process.
Like other Server side scripting languages, PHP is also equipped with a very handy file uploading mechanism. The PHP File Uploading system is a combination of setting some directives in PHP.ini file, creating a web form and creating a PHP script.

File Uploading Directives in PHP

  • file_uploads should set to on
  • upload_max_filesize set this directive to an integer value followed by capital M
  • upload_tmp_dir set this directive to a string value for example c:/wamp/myTmpFolder

Creating the HTML Form

<form action="scriptName.php" enctype="multipart/form-data" method="post">
<input name="fileName" />
<input name="myFile" type="file" />
<input name="submit" type="submit" />
Nothing is special except the enctype attribute which is here to handle large binary data.

Creating the PHP Script to handle the Uploaded File

The $_FILES superglobal array is responsible to hold all the information of the uploaded file wich is posted by an HTML form. So it is better to have a deep look at $_FILES superglobal array.
  • $_FILES['fileName']['tmp_name'] holds the temporary file name which is uploaded to the server but not moved.
  • $_FILES['fileName']['name'] holds the name of the file along with it's extension as it was stored on user machine(client).
  • $_FILES['fileName']['size'] holds the size of the file in bytes.
  • $_FILES['fileName']['type'] holds the type of the file e.g. for image files it returns image/jpeg.
  • $_FILES['fileName']['error'] returns a value from 0 to 4. 0 is returned if no error has occured during upload while number 1 to 4 represents different errors.
Remember "fileName" is the name of the file as assigned in HTML form. Now let's move to the example script.
    if( !is_uploaded_file($_FILES['myFile']['name']))
    if (! move_uploaded_file($_FILES['myFile']['tmp_name'],"c:\wamp\images\image1.jpg"))
      echo "File has not moved to the desired directory.";
       echo "File Uploaded successfully.";
  echo "File not uploaded.";
  • is_uploaded_file() function checks whether the file has been uploaded to the temporary directory, it returns true if the file is uploaded else it returns false.
  • move_uploaded_file moves the file to it's permanent location as desired by the developer.
Other information about the uploaded file exists in the $_FILE supergloabal. There are other advance concepts such as restricting the type and size of the file being uploaded, but for basic understanding this article is good enough.
Your comments are welcome.



  1. Amna said,

    Its a right way to upload a file.

    on July 29, 2013 at 3:06 AM  

Post a Comment