Advertisement
Google Ad Slot: content-top
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:
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:
Explanation of the Form Elements:
1. <form> Tag:
action="upload.php": Specifies the script to handle the file upload (upload.phpin 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
nameattribute (fileToUpload) is used to reference the uploaded file in PHP using$_FILES["fileToUpload"]. id="fileToUpload"is optional but helps in labeling the input element.requiredensures 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:
$target_diris the directory where the uploaded files will be stored.$target_fileis 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:
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:
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:
Complete Upload File PHP Script
The complete "upload.php" file now looks like this: