02 March 2011

Php File Uploader Script

Uploading a file to the server is very common and have become a essential part of any sophisticated web application. So in this article I am sharing the simplest php file uploader script, I will also show you guys the implementation of this php file uploader script. In order to make the implementation of this script easier, I am dividing the implementation of this file uploader script in three steps:

First Step: Taking file from user through an HTML form
In the first step we need to create an HTML form through which the user can upload his file. I am creating a sample HTML form, you can use any of your own, but dont forget to change "enctype" to "multipart/form-data". Changing the "enctype" is mandatory for uploading files.
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
  <table width="100%" border="0">
    <tr>
      <td>Select File:</td>
          <td><label>
          <input type="file" name="file" id="file" />
          </label></td>
        </tr>
        <tr>
          <td colspan="2"><label>
            <input type="submit" name="button" id="button" value="Upload" />
          </label></td>
        </tr>
  </table>
</form>



Second Step: Validation of Uploaded File
In the second step we will validate the uploaded file, in this script I am doing two validations first is there any file uploaded or not, and second whether the file extension is allowed or not.
<?php
$file = $_FILES['file'];
// Validating The Uploaded File
if ($_REQUEST['button']=="Upload")
{
    if(is_array($file))    # CHECK UPLOADED FILE FOR VALIDATION
    {
        $file['name'] = str_replace(" ","_",$file['name']);
        $file['name'] = str_replace("&","and",$file['name']);

        # CHECK FILE TYPE IF IT IS IMAGE JPG,GIF,PNG ETC
        $fnarr = explode(".", $file['name']);
        $file_extension = strtolower($fnarr[count($fnarr)-1]);
        $allowed_file_type = array('jpg','jpeg','gif','bmp');
        if(in_array($file_extension,$allowed_file_type))
        {
            #    GO AHEAD, THESE FILE TYPE ALLOWED
            $file['name'] = substr(md5($file['name'].time()),5,15).".".$file_extension;
        }
        else 
        {
            echo "Invalid File type! please upload only ".implode(",",$allowed_file_type)." files.";
            $_REQUEST['button']="NULL"; // setting button to null to stop uploading process
        }
    }
    else 
    {
        echo "Please upload any file";
        $_REQUEST['button']="NULL"; // setting button to null to stop uploading process
    }
} 
?>
Third Step: Copying Uploaded file to the Server
After validation we have to copy the uploaded file to the server. In this script I am saving the uploaded file in "images" directory, so dont forget to create the "images" directory.
<?php
//    Copying The Uploaded File to the server 
if($_REQUEST['button']=="Upload")
{
    //    UPLOADING PROCESS FOR FILE
    if(is_array($file))
    {
        $file_type    =    $file['type'];
        if(is_dir("images/"))
        {
            $file1    =    "images/".$file['name'];
            if(move_uploaded_file($file['tmp_name'],$file1))
            {
                $file    =    $file['name'];
                echo "File added successfuly";
            }
            else
                $file    =    "";
        }
        else
        {
            echo "dir images not exist";
            exit();
        }
    }
} 
?>
So guyz thats all, the complete php file uploader script is given below:
<?php
$file = $_FILES['file'];
// Validating The Uploaded File
if ($_REQUEST['button']=="Upload")
{
    if(is_array($file))    # CHECK UPLOADED FILE FOR VALIDATION
    {
        $file['name'] = str_replace(" ","_",$file['name']);
        $file['name'] = str_replace("&","and",$file['name']);

        # CHECK FILE TYPE IF IT IS IMAGE JPG,GIF,PNG ETC
        $fnarr = explode(".", $file['name']);
        $file_extension = strtolower($fnarr[count($fnarr)-1]);
        $allowed_file_type = array('jpg','jpeg','gif','bmp');
        if(in_array($file_extension,$allowed_file_type))
        {
            #    GO AHEAD, THESE FILE TYPE ALLOWED
            $file['name'] = substr(md5($file['name'].time()),5,15).".".$file_extension;
        }
        else 
        {
            echo "Invalid File type! please upload only ".implode(",",$allowed_file_type)." files.";
            $_REQUEST['button']="NULL"; // setting button to null to stop uploading process
        }
    }
    else 
    {
        echo "Please upload any file";
        $_REQUEST['button']="NULL"; // setting button to null to stop uploading process
    }
}

//    Copying The Uploaded File to the server 
if($_REQUEST['button']=="Upload")
{
    //    UPLOADING PROCESS FOR FILE
    if(is_array($file))
    {
        $file_type    =    $file['type'];
        if(is_dir("images/"))
        {
            $file1    =    "images/".$file['name'];
            if(move_uploaded_file($file['tmp_name'],$file1))
            {
                $file    =    $file['name'];
                echo "File added successfuly";
            }
            else
                $file    =    "";
        }
        else
        {
            echo "dir images not exist";
            exit();
        }
    }
}
?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
  <table width="100%" border="0">
    <tr>
      <td>Select File:</td>
          <td><label>
          <input type="file" name="file" id="file" />
          </label></td>
        </tr>
        <tr>
          <td colspan="2"><label>
            <input type="submit" name="button" id="button" value="Upload" />
          </label></td>
        </tr>
  </table>
</form>
If you have any queries or difficulties in the implementation of this script, feel free to comment and ask.

No comments: