File upload is the most used feature in web applications. PHP provides an easy way to upload file to the server. With PHP, you can upload files or images to the server by writing minimal code. In this tutorial, we’ll show you how to upload file in PHP and build a PHP script to upload file to the directory on the server. With this example PHP file upload script you can upload all types of files including images to the server in PHP.
At first, define HTML form elements to allow the user to select a file they want to upload.
Make sure <form> tag contains the following attributes.
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 server-side script (upload.php) for uploading the selected file to the server.
This upload.php file contains server-side code to handle the file upload process using PHP.
move_uploaded_file()
function we can upload a file in PHP.$targetDir
variable, specify the desire upload folder path where the uploaded file will be stored on the server.$allowTypes
variable, specify the types of the file in array format that you want to allow to upload.<?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;
?>
You can get the file type using the PHP pathinfo() function with the PATHINFO_EXTENSION flag. This can be used to allow the user to upload only the specific file types and restrict other file types. In this example script, we have allowed users to upload only JPG, JPEG, PNG, GIF, and PDF files, but you can upload any type of files using PHP.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
where does the file gets inserted to? is there a database connection to it?
hello i need the same code with multiple attachment files to be uploaded , please help
See this tutorial – https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/
Thank you so much, keep up the great work!