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' />
      </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&#91;'image'&#93;;
$temp = $file&#91;'tmp_name'&#93;;
if(is_uploaded_file($temp))
{
   if(move_uploaded_file($temp, $target_path.$file&#91;'name'&#93;))
   {
      echo "Upload successfull.";
      echo "File type is: ".$file&#91;'type'&#93;;
      echo "File size is: ".$file&#91;'size'&#93;/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\\”.

Advertisements

2 thoughts on “Uploading files with PHP

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s