Saturday, August 18, 2012

PHP - Handling File Uploads

In this article we will see how to upload files on PHP web page. You have to set up the form as a multipart form if you want to use file upload controls. In this example, that means you set the <form> element's enctype (encoding type) attribute to "multipart/form-data". You can also set the action attribute to the URL where you want the file data to be sent and the method to "post".

About the example : We have a file fileUploadForm.php, it will be used as a form to browse and upload file and of course it can have other form elements (text, checkbox, radobutton etc) as well. The action attribute is set to URL submitFile.php which will handle the file. It can specify the location where to save the file. Please see the self explanatory example below.



fileUploadForm.php


<html>
<head>
  <title> PHP - File upload form </title>
</head>
<body>

  <form action="submitFile.php" method="post" enctype="multipart/form-data">
  <table border="1" width="100%">
  <tr>
    <td width="50%">Name:</td>
    <td><input type="text" name="name"/></td>
  </tr>
  <tr>
    <td>File:</td>
    <td><input type="file" name="file"/></td>
  </tr>
  <tr>
    <td colspan="2" align="center"><input type="submit" value="Submit"/></td>
  </tr>
  </table>
  </form>

</body>
</html>


submitFile.php


<html>
<head>
  <title> PHP - File uploaded successfully </title>
</head>
<body>
<?php

  echo "Name : ".$_REQUEST["name"]."<br/>";

  if ($_FILES["file"]["error"] > 0)
  {
    echo "Error: ".$_FILES["file"]["error"]."<br/>";
  }
  else
  {
    echo "File name: ".$_FILES["file"]["name"]."<br/>";
    echo "File type: ".$_FILES["file"]["type"]."<br/>";
    echo "File size: ".($_FILES["file"]["size"] / 1024)." Kb<br/>";
    echo "File stored in: ".$_FILES["file"]["tmp_name"]."<br/>";

    $folderName = "Upload";

    //create a folder if it does not exist
    if (!is_dir($folderName)) {
    mkdir($folderName);
    }

    //check if file already exists
    if (file_exists($folderName."/".$_FILES["file"]["name"]))
    {
      echo $_FILES["file"]["name"]." already exists.";
    }
    else
    {
    //move the file from temp folder to desire folder
      move_uploaded_file($_FILES["file"]["tmp_name"],$folderName."/".$_FILES["file"]["name"]);
      echo "Stored in: ".$folderName."/".$_FILES["file"]["name"];
    }
  }

?>
</body>
</html>


Output





No comments:

Post a Comment