Uploading files with PHP

2008 July 15
tags:
by kunalbharati

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\\".

2 Responses leave one →
  1. 2008 July 15
    Joe Kiln permalink

    Wen i googled for a code to upload,i used to get big lines of code.Thnx for dis short code ;)

  2. 2009 March 23

    Greatings,
    Thanks for article. Everytime like to read you.

    Have a nice day
    Elcoj

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS