Uploading a file with PHP involves several steps, which include creating an HTML form for the file upload, writing a PHP script to handle the file processing, and ensuring the server settings and file permissions are correctly configured. Below is a detailed, step-by-step guide to achieve this along with some practical examples.
First, create an HTML form that allows users to select and upload a file. The form should use the `POST` method and include `enctype=“multipart/form-data”` which allows file data to be uploaded.
```
Create a PHP script called `upload.php` to handle the file upload. This script should check if a file has been uploaded, validate the file, and then move it to a specified directory on the server.
```
if ($_SERVER[‘REQUEST_METHOD’] = 'POST') {
// Check if a file has been uploaded
if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] = UPLOAD_ERR_OK) {
// Get file details
$fileTmpPath = $_FILES[‘uploadedFile’][‘tmp_name’];
$fileName = $_FILES[‘uploadedFile’][‘name’];
$fileSize = $_FILES[‘uploadedFile’][‘size’];
$fileType = $_FILES[‘uploadedFile’][‘type’];
- Ensure the PHP configuration file (`php.ini`) allows file uploads. Set `file_uploads` to `On` if it’s not already.
```
file_uploads = On
upload_max_filesize = 2M
post_max_size = 8M
```
- Ensure the upload directory (`./uploaded_files/`) exists and has appropriate write permissions.
```
mkdir ./uploaded_files/
chmod 755 ./uploaded_files/
```
An example of a successfully uploaded file will be saved in the `uploaded_files` directory with a new MD5-hashed filename such as `5d41402abc4b2a76b9719d911017c592.txt`.
1. PHP Manual – Handling File Uploads:
- [PHP: Handling File Uploads – Manual](https://www.php.net/manual/en/features.file-upload.php).
1. PHP Manual – File Handling:
- [PHP: Filesystem Functions – Manual](https://www.php.net/manual/en/ref.filesystem.php).
These sources provide comprehensive information on how file uploads are handled in PHP, including examples and detailed explanations of functions and best practices. By following this guide, you should be able to create a robust file upload feature in your PHP application.