May 20, 2009

Uploading files with PHP

During my recent project I learned about uploading files using. For uploading files with PHP first step is to create a HTML form:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">  <HTML>  

<BODY>    <FORM METHOD='POST' ACTION='upload.php' ENCTYPE='multipart/form-data'> 

<INPUT NAME="image" TYPE="file" />           <INPUT TYPE='Submit' VALUE='Upload' />  






For form the attribute ENCTYPE='multipart/form-data' is very important.

Next step is to create a PHP script upload.php which will upload the file:


// Path where the file will be uploaded  
$target_path = "/var/www/";  
$file  = $_FILES['image'];  
$temp = $file['tmp_name'];  
   if(move_uploaded_file($temp, $target_path.$file['name']))  
      echo "Upload successfull.";  
      echo "File type is: ".$file['type'];  
      echo "File size is: ".$file['size']/1024. " kb";  
      echo "File cannot be moved to $target_path";  
  echo "Unable to upload!";  

The target path given is an absolute path. I tried to give relative path but it didnt work. If you are using windows you can give path like "c:\\some_directory\\".

Click Here!