Skip to content

File Upload With PHP

I recently needed to handle a file upload using PHP and was pleasantly surprised by how easy it was. I am sharing my file upload test script below.

Create a file named “upload.php” with the following content:

<?php

{
  // Handle GET or POST
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    processRequest();
  } else { // GET
    showForm();
  }
}

// GET Handler
function showForm() {
?>
<html>
<body>

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

</body>
</html>
<?php
}

// POST Handler
function processRequest() {
  // Check for file upload errors
  if ($_FILES["file"]["error"] > 0) {
    echo "Error on File Upload: error code " . $_FILES["file"]["error"] . "<br>";
    return;
  }

  // Successful upload
  echo "Success on File Upload: Filename: " . $_FILES["file"]["name"] .
    ", Type: " . $_FILES["file"]["type"] .
    ", Size: " . ($_FILES["file"]["size"] / 1024) . " kB" .
    ", Location: " . $_FILES["file"]["tmp_name"] . "<br>";

  // Open the uploaded file (which will be deleted after this script ends)
  $file = fopen($_FILES["file"]["tmp_name"], "r");
  if (!$file) {
    echo "Error on File Read: Unable to open " . $_FILES["file"]["tmp_name"] . "<br>";
    return;
  }

  // Insert your code to consume the file content here!

  fclose($file);
  echo "Success on File Read: Opened and closed " . $_FILES["file"]["tmp_name"] . "<br>";
}

?>

To test, put this PHP file on your web server and browse to it.

Portions of the code above were sourced from W3Schools’ PHP File Upload page.

Leave a Reply

Your email address will not be published. Required fields are marked *