How To Upload File In PHP

In this article, we are going to learn how to upload files in PHP.

PHP gives upload file features that allow the uploading of binary and text files to the server.

PHP provides us to upload single and multiple files within little code.

Note some of the rules for HTML:

  1. Make sure the form uses the method=” post “.
  2. Also add enctype=”multipart/form-data” attribute in the form. if without these attributes try to upload a file, the file not upload.

Create an upload script:

The files get a using one global PHP variable $_FILES.

This variable has an associate double dimension array and stores all information about files.

The following variables are get using an input’s name attribute name:

  • $_FILES[‘file’][‘tmp_name’] − get a temporary file pathname of server
  • $_FILES[‘file’][‘name’] − get the actual name of the uploaded file.
  • $_FILES[‘file’][‘size’] − get the size in bytes of the uploaded file.
  • $_FILES[‘file’][‘type’] − get the type of the uploaded file.
  • $_FILES[‘file’][‘error’] − get the error code associated with this file upload.

move_uploaded_file() function:

The move_uploaded_file() function moves the uploaded file to a new location on the server.

This function checks internally if the file is uploaded through the POST request.

It moves the file if it is uploaded files through the POST request.

Now create an index.php file and add the below code in this file.

<!DOCTYPE html>
<html lang="en">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Blog Form</title>
  <link href="" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">		
  <script src=""></script>
  <div class="container">
    <div class="card mt-5">
      <div class="card-header">Upload File</div>
      <div class="card-body">
      <form id="form" action="upload.php" method="post" role="form" class="needs-validation" novalidate="" enctype="multipart/form-data">			
        <div class="row">
          <div class="col-md-6 mb-3"> 
            <label for="validationCustom01" class="pb-2">Select File</label></br> 
            <input class="form-control-file" type="file" name="image" id="validationCustom01" accept="image/png, image/jpeg, image/jpg, image/gif, .pdf" onchange="readURL(this);" required="">	
            <div class="invalid-feedback">
              Please Select Image file or PDF file.
        <button class="btn btn-primary" type="submit">Submit Form</button>
        <div class="msg"></div>
    (function () {
      'use strict'

      // Fetch all the forms we want to apply custom Bootstrap validation styles to
      var forms = document.querySelectorAll('.needs-validation')

      // Loop over them and prevent submission
      .forEach(function (form) {
        form.addEventListener('submit', function (event) {
        if (!form.checkValidity()) {

        }, false)

Create an uploads name folder and add image files to this folder.

Now create an upload.php file and add the below code of upload files in this file.

  if( !empty( $_FILES['image']['name'] ) && $_FILES['image']['size'] != 0 ){
    $file_name = $_FILES['image']['name'];
    $file_size = $_FILES['image']['size'];
    $file_tmp  = $_FILES['image']['tmp_name'];
    $file_type = $_FILES['image']['type'];
    $file_ext 		   = pathinfo( $file_name,PATHINFO_EXTENSION );
    $filename    	   = pathinfo( $file_name );
    $fname			   = $filename['filename'];
    $randomnumber	   = rand();
    $file_name_randaom = $fname . '_' . $randomnumber . '.' . $file_ext;
    $file_name_string  = str_replace(' ', '_', $file_name_randaom);

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

    if( in_array($file_ext,$extensions) === false ){
      echo "Extension is not allowed, please choose a JPEG or PNG file.";
    } else if ( move_uploaded_file($file_tmp,'uploads/'.$file_name_string) )  {
      echo "The file ". htmlspecialchars( basename( $file_name ) ). " has been uploaded.";
    } else {
       echo  "Failed to upload an image.";
  } else {
    echo 'File not attached.';


Submit a Comment

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


Select Categories