PHP Tutorials

PHP File Upload Tutorial: Step-by-Step with Examples

Upload files with PHP the right way: build the HTML form, read $_FILES, validate what arrives, and move it safely to your server.

Serhat ALPASLAN2 min read

PHP

To upload a file with PHP, you first use an HTML form. The most important parts of the form are the “enctype” and “method” attributes. The “enctype” attribute must be set to “multipart/form-data”, which is what makes the file upload work. The “method” attribute must be set to “post”.

Below is an example of a file upload performed using an HTML form:

<form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file" name="myfile">
  <input type="submit" value="Upload">
</form>

This form sends the data to a file named “upload.php” and uploads the file named “myfile”. The form data is submitted with the “submit” button.

The code on the PHP side should look like this:

<?php
if(isset($_FILES['myfile'])) {
  $errors= array();
  $file_name = $_FILES['myfile']['name'];
  $file_size = $_FILES['myfile']['size'];
  $file_tmp = $_FILES['myfile']['tmp_name'];
  $file_type = $_FILES['myfile']['type'];
  $file_ext=strtolower(end(explode('.',$_FILES['myfile']['name'])));

  $extensions= array("jpeg","jpg","png");

  if(in_array($file_ext,$extensions)=== false){
    $errors[]="extension not allowed, please choose a JPEG or PNG file.";
  }

  if($file_size > 2097152) {
    $errors[]='File size must be excately 2 MB';
  }

  if(empty($errors)==true) {
    move_uploaded_file($file_tmp,"images/".$file_name);
    echo "Success";
  }else{
    print_r($errors);
  }
}
?>

This code checks whether the uploaded file’s extension is among the allowed extensions. It also checks whether the file size is below the allowed size. If there are no errors, the file is saved to the “images” folder with “file_name”.

If any error occurs during this process, the errors are printed to the screen.

In this example, the file upload is handled in a file named “upload.php”. This file is called by the “action” attribute specified in the HTML form. The file named “myfile” can be accessed within the “FILES” array as $_FILES[‘myfile’]. The “name” property gives the file name, “size” gives the file size, “tmp_name” gives the path of the temporarily stored file, and “type” gives the file type.

In this code, the uploaded file’s extension must be “jpeg”, “jpg”, or “png”. The file size must also be less than 2MB. If the file meets these criteria, it is saved to the “images” folder with “file_name” using the move_uploaded_file() function. If any error occurs, the errors are printed to the screen.

The code in this example is a sample you can use to perform a file upload in a simple way. However, in real applications, you may need to take more security precautions during the upload and save information such as file names and sizes to a database.

Share it if it helped

Write a comment