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">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Blog Form</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">		
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
</head>
<body>
  <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.
            </div>
          </div>
        </div>
        <button class="btn btn-primary" type="submit">Submit Form</button>
        <div class="msg"></div>
      </form>
      </div>
    </div>
  </div>
  <script>
    (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
      Array.prototype.slice.call(forms)
      .forEach(function (form) {
        form.addEventListener('submit', function (event) {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }

        form.classList.add('was-validated')
        }, false)
      })
    })()
  </script>
</body>
</html>

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.

<?php
  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.';
    
  }
?>

Output:

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories