How to upload file to server in PHP

  •  
  •  
  •  
  •  
  •  
  •  

Upload file to server in PHP is very easy. A simple PHP script can be used with a simple HTML form to allow users to upload file to server. You can upload any kind of file such as videos, pdfs, images, zip, docx and so on. Before proceeding, you need to ensure that PHP is configured to allow uploads and for that open php.ini file and verify the file_uploads directives is set On.

file_uploads = On

 

Objectives

  1. Build an HTML form.
  2. Receive form data.
  3. Validate the data and upload file to server.
  4. Display message.

 

Build an HTML form — 

At first we have to create an html form where users can select a file from file dialog window for upload. Let’s create a php file called index.php and write the below code in it within <body> tag.

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

action=”index.php” –  when form is submitted it submitted to itself means to index.php. Always remember that when you want to upload file to server you must specify enctype=”multipart/form-data”, it is specify the mime type, without declaring the enctype you can submit the form but cannot upload file to server.

 

Receive form data

Now when the user clicks submit, the form data will be posted to the server and the user will be redirected to the upload-file.php with the form values. Here you will receive the data and will manipulate them as you need. Now create another PHP file called upload-file.php and write the below codes in it.

<?php
if(isset($_POST['submit'])) {
  $msg = "";
  
  // Default path, where files or images will be stored.
  $target = "upload/";
  
  // Allowed file types.
  $allowedExtensions = array("jpg","JPG","jpeg","JPEG","gif","GIF");
  
  // Maximum file size to be allowed
  $allowedSize = 500; //in KB
  $isUploaded = 0;
  $file = "";
?>

First you will check if the form is submitted or not. if(isset($_POST[‘submit’])) – the isset() function is used to check whether a variable is set or not. Set a default directory where to upload file to server, in this case “upload” is the default directory. $allowedExtensions is an array with some predefined file extensions which are allowed to upload. Except these file extensions no other file types are allowed. Maximum file size is 500 KB, more than that is not allowed.

 

Validate the data and upload file to server

Although allowing users to upload file to server in PHP is very but it is very risky also. So be careful about it. Have a look at the following code and append the code in the upload-file.php file.

<?php
  // Check if any file is selected or not through file dialg box
  if(isset($_FILES) && $_FILES['uploadFile']['size'] > 0) {
    $target .= $_FILES['uploadFile']['name'];
    
    // Check if the file already exists or not in the upload folder
    if(!file_exists($file)) {
    
      // Get the uploaded file extension
      $ext = pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION);
      
      // Check if the extension is allowed or not
      if(in_array($ext, $allowedExtensions)) {
        
        // Get the file size
        $file_size = $_FILES['uploadFile']['size'] / 1024;
        
        // Check if the file size is within maximum allowed file size
        if($file_size <= $allowedSize) {
        
          // Copy and save the file to the upload folder with the original name
          $isUploaded = copy($_FILES['uploadFile']['tmp_name'], $target);
          if($isUploaded == 1) $msg = "File successfully uploaded!";
          else $msg = "File upload failed!";
        } else {
          $msg = "Maximum file size should be less than ".$allowedSize." kb!"; 
        }
      } else {
        $msg = "Wrong file type!";
      }
    } else {
      $msg = "File already exists!";
    }
  } else {
    $msg = "Nothing is selected!";
  }
}
?>

 

$_FILES – is a global array variable which holds data about a file, such as name, size, temporary location, error etc.

isset($_FILES)– It checks whether $_FILES variable is set or not.

$_FILES[‘uploadFile’][‘size’] > 0 —  It checks the size of the file, if anything is chosen then it must have a size greater than 0.

file_exists() – It checks if the file is already exists or not in the upload directory.

pathinfo($_FILES[‘uploadFile’][‘name’], PATHINFO_EXTENSION)  — It returns the extension of the chosen file.

in_array($ext, $allowedExtensions) —  It returns true if the extension is allowed to upload.

$_FILES[‘uploadFile’][‘size’] – It returns the size of the file in bytes, dividing by 1024 it returns the size in KB.

if($file_size <= $allowedSize) – It checks if the size is less than or equals to the maximum allowed size or not.

copy($_FILES[‘uploadFile’][‘tmp_name’], $target) — After all validations the file is uploaded. Copy() function returns 1 if file is successfully uploaded to the server otherwise it returns 0.

You can skip some validation if not required.

 

Display message

Whether the file is uploaded or not a message will always display.

<?php echo "<div class='msg-div'>".$msg."</div>"; ?>

 

If you enjoy this article – “Upload file to server in php” and think it is useful then please share this article with others.

 

About Mitrajit

Leave a Reply

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

Prove you are a human *