In this article we are going to cover File Upload in PHP with Examples.
Table of Contents
What is file upload in PHP?
PHP allows you to upload single and multiple files through few lines of code only. And it is easy to upload files to the server. PHP file upload features allows you to upload binary and text files both.
PHP $_FILES:
In PHP, global $_FILES contains all the information of file. The help of $_FILES global, we can get file name, file type, file size, temp file name.
$_FILES[‘filename’][‘name’]
Returns file name
$_FILES[‘filename’][‘type’]
Returns MIME type of the file.
$_FILES[‘filename’][‘size’]
Returns size of the file in bytes.
$_FILES[‘filename’][‘tmp_name’]
Returns temporary file name of the file which was stored on the server.
$_FILES[‘filename’][‘error]
Returns error code associated with this file.
Create The HTML Form
Next, create a HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Output:
Upload.php
<?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Conclusion:
In this article we have covered File Upload in PHP with Examples.
Related Articles:
- Introduction about PHP [PHP 7]
- Date and Time in PHP with Examples [2 Steps]
- 3 Data Types in PHP with Examples
- Form Validation in PHP with Examples
- 3 Types of Arrays in PHP with Examples
- 4 Types of Loop in PHP with Examples
- 4 Types of String in PHP with Examples
- Cookies in PHP with Examples [2 Steps]
Reference: