How to Upload File in PHP


File upload is a most used feature in the web application. PHP provides an easy way to upload file to the server. With PHP, you can upload file or images to the server by writing minimal code. In this tutorial, we’ll provide a PHP script to upload file to the directory on the server. Using our PHP file upload script you can upload all types of files including images to the server in PHP.

Upload Form HTML

At first, an HTML form needs to be created that allow users to choose a file they want to upload.
Make sure <input> tag contains the following attributes.

  • method=”post”
  • enctype=”multipart/form-data”

Also, make sure <input> tag contains type="file" attribute.

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

The above file upload form will be submitted to the upload.php file for uploading file to the server.

Upload File in PHP (upload.php)

PHP provides a function called move_uploaded_file() that moves an uploaded file to a new location. Using move_uploaded_file() function we can upload a file in PHP.
The following code is used to upload file in PHP. Specify the directory in $targetDir variable, where the uploaded file will be placed. Also, define the file types that you want to allow for uploading.

<?php
$statusMsg 
'';

//file upload path
$targetDir "uploads/";
$fileName basename($_FILES["file"]["name"]);
$targetFilePath $targetDir $fileName;
$fileType pathinfo($targetFilePath,PATHINFO_EXTENSION);

if(isset(
$_POST["submit"]) && !empty($_FILES["file"]["name"])) {
    
//allow certain file formats
    
$allowTypes = array('jpg','png','jpeg','gif','pdf');
    if(
in_array($fileType$allowTypes)){
        
//upload file to server
        
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
            
$statusMsg "The file ".$fileName" has been uploaded.";
        }else{
            
$statusMsg "Sorry, there was an error uploading your file.";
        }
    }else{
        
$statusMsg 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
    }
}else{
    
$statusMsg 'Please select a file to upload.';
}

//display status message
echo $statusMsg;
?>

Recommended Tutorials For You

Leave a reply

CONNECT WITH CODEXWORLD