Wednesday, 6 June 2012

Uploading a file using php


<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

  <?php
 ************************echo $_FILES["file"]["type"];************************
  echo $_FILES["file"]["name"];
  echo $_FILES["file"]["size"];
  $_SESSION["file"]=$_FILES["file"]["name"];
// this if block is used to check the file extension. Only files with certain extensions are allowed.
  if ((($_FILES["file"]["type"] == "application/force-download")  //for excel file
  || ($_FILES["file"]["type"] == "image/jpeg")  //for .jpeg files
  || ($_FILES["file"]["type"] == "application/pdf"))  //for pdf files

  && ($_FILES["file"]["size"] < 2000000)) //used to limit size of file
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("folder_name/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],"folder_name/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "folder_name/" . $_FILES["file"]["name"];
      }
    }
}
  else
  {
  echo "Invalid file";
  }
  ?>
 folder_name: Folder that you need to keep the uploaded file.(directory)

File type for uploading files in php

 

 ********************** This echo is helpful if you dont know the file type that you need to upload. Echo gives you the type of file and that can be used in the if condition.

for eg: You need to upload a file with extension .pdf. In the above code, only certain extensions are allowed.(pdf is allowed here).       echo $_FILES["file"]["type"];   will give you the extension of file you are trying to upload. Just copy and paste the extension in the if condition for accepting that type of files to get uploaded.


No comments:

Post a Comment