PHP Basic Tutorial
MySQL Connection
PHP Advanced
PHP allows you to upload files (e.g., images, PDFs, documents) using HTML forms and PHP scripts.
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:
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:
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">
:
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:
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_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.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:
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:
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:
The complete "upload.php" file now looks like this: