PHP File Upload

PHP allows you to upload files (e.g., images, PDFs, documents) using HTML forms and PHP scripts.

Configure The "php.ini" File


The php.ini file controls various PHP settings, including file upload limits.


In your "php.ini" file, search for the file_uploads directive, and set it to On:

file_uploads = On

Create The HTML Form


To allow users to upload files through a webpage, you need to create an HTML form that includes an <input> element of type file.


Additionally, you must set the form's enctype attribute to multipart/form-data so that the form can handle file uploads.

Here is a simple example of an HTML file upload form:

Example
<!DOCTYPE html>
<html lang="en">
<body>
<h2>Upload Your File</h2>
<!-- File Upload Form -->
<form action="upload.php" method="post" enctype="multipart/form-data">
<!-- Input for file upload -->
<label for="fileToUpload">Select file to upload:</label>
<input type="file" name="fileToUpload" id="fileToUpload" required>
<!-- Submit button -->
<br><br>
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>

Explanation of the Form Elements:

1.  <form> Tag:

  • action="upload.php": Specifies the script to handle the file upload (upload.php in this case).
  • method="post": This tells the form to send data using the POST method, which is required for file uploads.
  • enctype="multipart/form-data": This encoding type is essential for handling file uploads. It allows files to be sent along with other form data.


2. <input type="file">:

  • The name attribute (fileToUpload) is used to reference the uploaded file in PHP using $_FILES["fileToUpload"].
  • id="fileToUpload" is optional but helps in labeling the input element.
  • required ensures that the user must select a file before submitting the form.


3. Submit Button:

  • When the user clicks the submit button, the form data (including the uploaded file) is sent to the server for processing.

Create The Upload File PHP Script


Once you’ve created your HTML form for file uploads, you’ll need a PHP script to handle the uploaded file and store it on your server.

Here is an example PHP script (upload.php) that processes the file upload:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
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;
}
}
?>
  • $target_dir is the directory where the uploaded files will be stored.
  • $target_file is the full path to the uploaded file, which is a combination of the target directory and the file name.
  • $uploadOk=1 is not used yet (will be used later)
  • $imageFileType holds the file extension of the file (in lower case)
  • Next, check if the image file is an actual image or a fake image

Check if File Already Exists

Now we can add some restrictions.


If the file already exists in the target directory, the script will prevent the upload and show an error. Then, $uploadOk is set to 0:

// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

Limit File Size


The file input field in our HTML form above is named "fileToUpload".

Now, we want to check the size of the file. If the file is larger than 500KB, an error message is displayed, file will not be uploaded, and $uploadOk is set to 0:

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}

Limit File Type


The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0:

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}

Complete Upload File PHP Script

The complete "upload.php" file now looks like this:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
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;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} 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.";
}
}
?>

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.