Monday, October 10, 2011

File upload using php

Create an Upload Html Form

<form action="uploadfile.php" method="post" enctype="multipart/form-data">
<label for="title">Title</label> <input id="title" name="title" type="text" size="50">
<label for="file">Filename:</label> <input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>

The enctype attribute of the 'form' tag specifies which content-type to use when submitting a form. "multipart/form-data" is used when a form requires binary data (the contents of a file), to be uploaded
The type="file" attribute of the 'input' tag specifies that the input should be processed as a file. there will be a browse-button near the input field.

Create PHP file 

<?php
if (($_FILES["file"]["type"] == "image/jpg") && ($_FILES["file"]["size"] < 1048576))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] ;
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] ;
    echo "Type: " . $_FILES["file"]["type"] ;
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " KB";
    echo "Temporary file: " . $_FILES["file"]["tmp_name"] ;

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "File error.";
  }
?>



$_FILES array contain file information.

$_FILES["file"]["name"] - the name of the uploaded file
$_FILES["file"]["type"] - the type of the uploaded file
$_FILES["file"]["size"] - the size in bytes of the uploaded file
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
$_FILES["file"]["error"] - the error code resulting from the file upload.

No comments:

Post a Comment