In this tutorial, I’m going to make simple html form, to grab the file information from user’s device then save the selected image or file to the server using php. If you’re looking for a php image upload tutorial, you’re in the right place. In almost all type of websites uploading images is common where you use them for either gallery, profile picture or any other task. Alright, I’ll explain each step in brief. You better concentrate on the comments given in php scripting, everything defines itself.
Creating form
To create a simple html form, make a .htm, .php or any other file. It doesn’t matter until you describe the action of form to the file itself. Here is the form we’re going to use in this tutorial:
?
Upload new profile picture! |
In the above form, we’ve described the method to post and the name of the file to the photo. These are one of sensitive information we need to take care about while transferring data over network. Now, let’s create upload.php where all the script will work!
Creating upload.php
After retrieving data using html form, everything will be sent over upload.php as we’ve described action of form to upload.php. Instead of $_POST[], there is a command named $_FILES[] in php, made for only files selected through forms. Basic syntax of $_FILES[] is:
?
| 1 | $_FILE[‘filename’][‘fileproperty’]; |
In this tutorial, filename is photo and there are in-built properties [ or reserved variables ] for $_FILE command. These properties are given below:
- $_FILES[‘filename’][‘name’] – Name of the uploaded file
- $_FILES[‘filename’][‘type’] – Type of the uploaded files
- $_FILES[‘filename’][‘size’] – Size of uploaded files ( in bytes )
- $_FILES[‘filename’][‘error’] – Error while uploading files
- $_FILES[‘filename’][‘tmp_name’] – Temporary name of uploading files
Now, let’s start with php scripting:
?
| 1 |
Above php script is perfect for first time image uploading with a little bit validation. If you want to store information of uploaded file on mysql database, simply add your sql query in the box where move_uploaded_file command take place. Basically, file type form submission stores temporary file on the server, to make it permanent we do use move_uploaded_file(photo-tempname, location), as everything cleared in above example! Now, you’ve successfully uploaded an image to your server disk, to ensure that you can see your server’s folder images/userpics folder. For any question answer, reply. |