Uploading files with PHP

113

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’ />  

</FORM>  

</BODY>

</HTML> 

 

 

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:

 

<?php  
// Path where the file will be uploaded  
$target_path = “/var/www/”;  
 
$file  = $_FILES[‘image’];  
$temp = $file[‘tmp_name’];  
if(is_uploaded_file($temp))  
{  
   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”;  
   }  
   else  
   {  
      echo “File cannot be moved to $target_path”;  
   }  
}  
else  
{  
  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\”.