How to upload a file in PHP ?
Last Updated :
01 Mar, 2022
In this article, we will learn how to upload a file using PHP. Let us first understand some basic configurations.
Approach: In your "php.ini" file, search for the "file_uploads" parameter and set it to "On" as mentioned below.
file_uploads = On
In the "index.html" file, the enctype must be multipart/form-data and the method must be POST.
<form action="fileupload.php"
method="POST" enctype="multipart/form-data">
Example 1: First, we created an HTML file so that we can upload a file using a form through the post method, and also it is important to make sure that the method is post method.
In "uploading_file.php", we first store the directory name and file information from the post method, and then we check for the existence of the directory, validity of extensions. We can check if the file size is less than the maximum file size along with the existence of the file so that we can upload the file after all the validations.
The extensions which are allowed can be changed or added in an array according to the requirements of the program.
index.html
<!DOCTYPE html>
<html>
<body>
<form action="uploading_file.php"
method="post"
enctype="multipart/form-data">
Directory<input type="text"
name="dirname"
id="dirname">
<br>
Select image to upload:
<input type="file"
name="fileToUpload"
id="fileToUpload">
<br>
<input type="submit"
value="Upload Image"
name="submit">
</form>
</body>
</html>
uploading_file.php
<!DOCTYPE html>
<?php
$target_dir = $_POST["dirname"]."/";
$target_file = $target_dir
. basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
if($_SERVER["REQUEST_METHOD"] == "POST") {
// To check whether directory exist or not
if(!empty($_POST["dirname"])) {
if(!is_dir($_POST["dirname"])) {
mkdir($_POST["dirname"]);
$uploadOk = 1;
}
}
else {
echo "Specify the directory name...";
$uploadOk = 0;
exit;
}
// Check if file was uploaded without errors
if(isset($_FILES["fileToUpload"]) &&
$_FILES["fileToUpload"]["error"] == 0) {
$allowed_ext = array("jpg" => "image/jpg",
"jpeg" => "image/jpeg",
"gif" => "image/gif",
"png" => "image/png");
$file_name = $_FILES["fileToUpload"]["name"];
$file_type = $_FILES["fileToUpload"]["type"];
$file_size = $_FILES["fileToUpload"]["size"];
// Verify file extension
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
if (!array_key_exists($ext, $allowed_ext)) {
die("Error: Please select a valid file format.");
}
// Verify file size - 2MB max
$maxsize = 2 * 1024 * 1024;
if ($file_size > $maxsize) {
die("Error: File size is larger than the allowed limit.");
}
// Verify MYME type of the file
if (in_array($file_type, $allowed_ext))
{
// Check whether file exists before uploading it
if (file_exists("upload/" . $_FILES["fileToUpload"]["name"])) {
echo $_FILES["fileToUpload"]["name"]." is already exists.";
}
else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
echo "The file ". $_FILES["fileToUpload"]["name"].
" has been uploaded.";
}
else {
echo "Sorry, there was an error uploading your file.";
}
}
}
else {
echo "Error: Please try again.";
}
}
else {
echo "Error: ". $_FILES["fileToUpload"]["error"];
}
}
?>
</body>
</html>
Output:
enter directory name and choose file
In the "uploads" folder of the working folder, the user can find the uploaded "gfg_sample.png" file.
Similar Reads
How to Upload File in Python-Flask File uploading is a typical task in web apps. Taking care of file upload in Flask is simple all we need is to have an HTML form with the encryption set to multipart/form information to publish the file into the URL. The server-side flask script brings the file from the request object utilizing the r
2 min read
How to Upload Files in JavaScript? We upload files using JavaScript, for this we have to capture form elements, gather information from FormData for easier file uploads, intercept submission events, and utilize Fetch API for asynchronous server requests, for enhanced user experience and efficient data handling. ApproachProject Setup:
1 min read
Write a Code To Upload A File in PHP? PHP makes it easy to upload files in web applications, whether it's for images, documents, or other types of files. With its built-in functions, uploading files to the server becomes a simple task. However, it's important to be cautious when allowing file uploads, as they can pose security risks. Al
6 min read
How to write Into a File in PHP ? In this article, we are going to discuss how to write into a text file using the PHP built-in fwrite() function. The fwrite() function is used to write into the given file. It stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first. The file
2 min read
How to access actual name of uploaded file in PHP ? In PHP, we can access the actual name of the file which we are uploading by keyword $_FILES["file"]["name"]. The $_FILES is the by default keyword in PHP to access the details of files that we uploaded.The file refers to the name which is defined in the "index.html" form in the input of the file.The
2 min read