Monday 18 March 2013

Uploading file using in php

Welcome to my new post !!!!


In this post we will be seeing how can we upload files from client side to the server folder.
It is very common requirement but prople often find it a atough job..
I will try to explain it as possible as I can simultaneously keeping myself simple and consice.

So lets start with it.


PHP INI SETTINGS 

You need to check certain settings in php.ini file to make your upload successful
use phpinfo() to check the value of these settigs

  • file_uploads               : allow file upload or not
  • upload_max_filesize   : maximum size of file that can be uploaded      
  • memory_limit             : maxiumum memory limit that   can be allocated to script 
  • max_execution_time   : maximum time for which file can be executed
  • post_max_size           :  mamixmum post size

First of all we have to create a form that will be used to get the file from the client.

<html>

<head>

<title>Learn Image Uploading</title>

</head>

<body>

<form method='post' enctype='multipart/form-data' action='uploadFile.php'>

<label for='imgFile'>Choose Image</label>

<input name='imgFile' id='imgFile' type='file'/><br/>

<input type='submit' value='upload'>

</form>

</body>

</html>



Things to note:

The main difference in this form and other forms is  enctype  attribute. This attribute specifies the type of the content that is being submitted .Its default value of this attribute is "application/x-www-form-urlencoded". The value "multipart/form-data" is used whenever we are submitting or uploading any kind of file.

If we do not use it it will not populate $_FILES array at server side.
We will be learning about this later on ..

  •   Now create a folder on server which will be saving the images that are uploaded say "uploads"
  •   You will then require a php script  to handle the file uploads .


<?php
#---- ini settings (ini)----
ini_set('display_errors', '1');
#-------------(/ini)--------
$is_file_uploaded  = (!empty($_FILES))?true:false;
if($is_file_uploaded)
{
  $is_error = ($_FILES['imgFile']['error'] == 0)?false:true;
  if( ! $is_error)
   {
      $fileDetails = $_FILES['imgFile'];
      #--------- details of the file being uploaded (/details)----
      echo "File Name: {$fileDetails['name']}: <br/>";
      echo "File Type: {$fileDetails['type']} <br/>";
      echo "File temp name (Name used while uploading) : {$fileDetails['tmp_name']} <br/>";
      echo "File Size : {$fileDetails['size']} <br/>";
      #---------------(/details)------------------------------
     
      #------------ move the uploaded file to server(move uploaded file)---------
      $temp_file         = $fileDetails['tmp_name'];
      $path              = "uploads/{$fileDetails['name']}";
      $move              = move_uploaded_file($temp_file, $path);  // move the file from temp steam to server
      #--------------------------(/move uploaded file)---------------------------
      if($move)
      {
      echo "File successfully Uploaded";
      }
      else
      {
       echo "OOPS!! There is some error";
      }
   }
}
?>

Now open the "uploads" folder and check for the file.
  • make sure the path of folder is correct and you have proper permissions on that folder
The script I have shown above is without any restriction .. Obviously you will not want anyone to upload file of any type with any size ...

So lets add some validation to our uploading script


<?php
#---- ini settings (ini)----
ini_set('display_errors', '1');
#-------------(/ini)--------

$is_file_uploaded  = (!empty($_FILES))?true:false;
if($is_file_uploaded)
{
 $is_error = ($_FILES['imgFile']['error'] == 0)?false:true;
  if( ! $is_error)
   {
      $fileDetails = $_FILES['imgFile'];
      
      #--------- details of the file being uploaded (/details)---- 
      echo "File Name: {$fileDetails['name']} <br/>";
      echo "File Type: {$fileDetails['type']} <br/>";
      echo "File temp name (Name used while uploading) : {$fileDetails['tmp_name']} <br/>";
      echo "File Size : {$fileDetails['size']} <br/>";
      #---------------(/details)------------------------------
      
      
      #----------   resctrictions ----------------------------
      
      // Restrict the file size to be 50 kb
      $is_valid_size  = ($fileDetails['size'] < 51200)?true:false;
      
      // resctrict valid file type to be png,jpg,gif,jpeg
      
      $validFileTypes = array('image/jpeg','image/jpg','image/png','image/gif');
      $is_valid_type  = (in_array($fileDetails['type'], $validFileTypes)==true)?true:false;  
      
      #---------------(/restrictionns)------------------------
      
      #------------ move the uploaded file to server(move uploaded file)---------
      $temp_file         = $fileDetails['tmp_name'];
      $path              = "uploads/{$fileDetails['name']}";
      
      $is_file_existing  = (file_exists($path))?true:false;
      
      if($is_file_existing)
      {
       @unlink($path);
      }
      
      
      // move file only if size and file type is valid
      if($is_valid_type && $is_valid_size)
      {
       $move           = move_uploaded_file($temp_file, $path);  // move the file from temp steam to server
      }
      else
      {
       echo "Please check Your file type('png,jpg,gif,jpeg') and file size(max 50kb)";
      }
      
      #--------------------------(/move uploaded file)---------------------------
      if($move)
      {
       echo "File successfully Uploaded";
      }
      else
      {
       echo "OOPS!! There is some error";
      }
   }
}
?>
Congrats .. You are done .. !!

2 comments:

  1. But in this form i can put some other data too or do i have to make another form with no enctype to pick the rest of the data???

    ReplyDelete
  2. Sorry for late reply... You need not to create any other form .... you can pass whatever data you want with this enctype

    ReplyDelete