Reading time: 3 minutes
This tutorial will help you learn how you can accept a file uploaded using HTML tag and process it using PHP code.
To accept a file upload using HTML, you need to write an tag with POST as its method attribute and multipart/form-data as its enctype attribute.
Create a file named index.html with the following content:
PHP will accept a file uploaded by HTTP POST method in the $_FILES variable.
Next, create a PHP file named action.php with the following content:
PHP uses the tag’s name attribute to name the array object it appends to the $_FILES variable.
The last step is to add the name of the PHP file as the form’s action attribute:
With that, you now have a working PHP script to accept file uploads.
You need to run a PHP server and upload a file using the index.html page.
The result will be shown in action.php page as shown below:
The output above means the image has been successfully uploaded to the tmp/ folder.
To put the file in a folder on your computer, you need to use the PHP move_uploaded_file() function.
For example, you can add the following code in action.php file:
You need to get the tmp_name from the uploaded file because that’s where PHP is keeping the uploaded file.
Then, get the complete path for the new file location, including the directory and the file name.
In the above script, the new file location is in ./assets/book.pdf , so PHP will save the uploaded file there.
Now you’ve learned how to upload a file using a PHP script.
You can also add more code to serve as validations before uploading the file.
For example, you can check the extension and allow only jpeg , png , or jpg image extensions to be uploaded:
Or you can also limit the maximum file size allowed for the file:
You can extend the PHP file upload script as you need.
I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Type the keyword below and hit enter
Click to see all tutorials tagged with: