Easy File Uploading Solution For PHP

Uploading files/images is a task that is required in almost all web applications.

While uploading file is a very simple task, still lot of beginners in PHP get stuck in this step. So in this post I decided to share the functions I learned while I was a beginner, and I still continue to use them because of it’s simplicity and usefulness.

For all my file uploading needs I use the class.upload.php written by Colin Verot. Ok, I know all about PHP functions like move_uploaded_file() and is_uploaded_file(), still I prefer to use class.upload.php file because, this file provides me with good set of image manipulation functions along with a neat way to know when a file has been uploaded.

So, let’s get started on, how to easily upload a file in PHP.

First, let’s create a simple HTML form for uploading files.

 <form action="file-upload.php" method="post" enctype="multipart/form-data">

  Upload file: <input type="file" name="fileupload">

                  <input type="submit" value="save">

 </form>

It is important to note that the form’s enctype is  multipart/form-data. This a place where novice developers make lot’s of mistake, they will forget to add enctype attribute to form and them spends hours thinking why they are not able to upload files or images.

Now, that we have a form to upload files, let’s see how we can handle file uploads on server.

I am going to cover four scenario’s here.

Simple File Uploading

 if($_FILES['fileupload']['error']!=4)
 {
   $handle = new Upload($_FILES['fileupload']);
   if ($handle->uploaded)
   {
     $handle->Process('images/originalview/');
     // file uploaded do whatever you want to do now.
   }
   else
   {
       echo '  Error: ' . $handle->error;
   }
 }

What we are doing above is basically, first testing if ‘fileupload’ field in the form is not empty. If it is not empty, then we create an instance of upload class, by passing the $_FILES object.

Then we check if file specified in fileupload field has been successfully uploaded on the server or not.

If it has been uploaded then we move that file from temporary location to folder where we want to store the uploaded file. In our case it is originalview folder in images folder.

Now that file is uploaded and moved to server you can store the meta data of the images to database or use it whatever way you want.

Renaming a File, After Uploading

if($_FILES['fileupload']['error']!=4)
{
  $handle = new Upload($_FILES['fileupload']);
  if ($handle->uploaded)
  {
     $handle->file_new_name_body =date('YmdHis');
     $handle->Process('images/originalview/');
     if ($handle->processed)
     {
        //file is renamed and stored in images/originalview folder.
     }
   }
   else
   {
      echo '  Error: ' . $handle->error . '';
   }
}

Now, simply uploading a file, without renaming it in some sort of way, can result in a file getting overwritten. To avoid this situation it is recommended that you rename the file based at least of date and time of image upload. Off course this is still not a perfect solution to avoid filename conflicts, still we can use this for normal cases.

As shown in the code above, the only difference is that we specify a new body name of the file that we uploaded, before moving it to final destination.

By using processed variable of handle object, we can ensure that file has been successfully renamed.

Resizing Image After Uploading

if($_FILES['fileupload']['error']!=4)
{
   $handle = new Upload($_FILES['fileupload']);
   if ($handle->uploaded)
   {
     $file_body =date('YmdHis');
     $handle->image_resize          = true;
     $handle->image_ratio        = true;
     $handle->image_x               = 100;
     $handle->image_y               = 100;
     $handle->file_new_name_body =$file_body;
     $handle->Process("images/thumbnail/");

     $handle->image_resize          = true;
     $handle->image_ratio        = true;
     $handle->image_x               = 150;
     $handle->image_y               = 150;
     $handle->file_new_name_body =$file_body;
     $handle->Process("images/imageview/");
    }
    else
    {
      echo '  Error: ' . $handle->error . '';
     }
}

When it comes to file uploading, chances are that the file would be an image file, and we need to resize it, to make sure it fit’s within the fixed dimensions. Now resizing an image with proper aspect ratio is not an easy job.

But thanks to class.upload.php, it has become a trivial task. As shown in the code above, all you have to do is to set the image_resize and image_ratio property to true and specify the maximum allowed dimensions for the image. All the rest will be taken care by upload class.

Also sometimes it might be necessary to create multiple images of variable sizes even that can be archived easily as show above.

Handling Multiple File Uploads

 $files = array(); 
foreach ($_FILES['fileupload'] as $k => $l)
{
    foreach ($l as $i => $v)
    {
        if (!array_key_exists($i, $files))
        $files[$i] = array();
        $files[$i][$k] = $v;
    }
}

Sometimes it might be necessary to allow user to upload more then one file to the webserver. In that case we can name all our input fields something similar to “fileupload[]“.

Then we can use the logic above to  create an new array out of $_FILES, and then pass that array to upload class as shown below.

I have taken this example directly from the test file provided with class.upload.php.

 foreach ($files as $file)
 {
    // we instantiate the class for each element of $file 
     $handle = new Upload($file);
   // then we check if the file has been uploaded properly
   // in its *temporary* location in the server (often, it is /tmp)
   if ($handle->uploaded)
   {
      $handle->Process("./test/");
      if ($handle->processed)
      {
         // everything was fine !
      }
      else
      {
         echo '  file not uploaded to the wanted location';
         echo '  Error: ' . $handle->error . '';
      }
    }
    else
    {
        echo '  Error: ' . $handle->error . '';
    }
 }

While I was writing this I found another article which has covered usage of class.upload.php, you may find it useful.

I think this is the easiest way to handle file uploads in PHP, I would love to know how you used to manage the file uploads and image resizing.

6 thoughts on “Easy File Uploading Solution For PHP

  1. Im confused. What do I have to do with class.upload.php? do i have to include it at the beginning of the file-upload.php? It’s not working for me =o(

  2. if($_FILES[‘my_field’][‘error’]!=4)
    {
    $handle = new Upload($_FILES[‘my_field’]);
    if ($handle->uploaded)
    {

    $str=”image”;
    $handle->file_new_name_body =$str;
    $handle->Process(‘../cart/image/coins/’);
    if ($handle->processed)
    {
    echo “file is renamed and stored in images/originalview folder.”;
    }
    }
    else
    {
    echo ‘ Error: ‘ . $handle->error . ”;
    }
    }

    Now I have store image name with full extension but when i call $str then it comes only ‘image’ not extension . how i can get image name with extension. or any function in claa.upload.

    plsz help

Comments are closed.