Utilizing the ability to upload files with PHP can be a great asset to your site. You will find that the code to initiate a file upload is quite simple, and most of the script is based on limitations, such as: file type filtering, cross browser recognition and error detection. You want to make sure that images are being uploaded, and not php scripts with an image header. You also want to write your code so that it will execute properly for the various popular web browsers used. It is vital to the script to be provided with all of the required input to complete the request.
Based on the design that I will discuss in the article, the overall construction of this script will be encapsulated in an IF statement (2 parts - true and false), with the condition based on the status of a button. The basic algorithm for the condition will be: If the submit button was pressed, evaluate image to upload. If not (submit not pressed), show the form to upload the image.
Input Form and Elements
Your first step is to build a form to which the user will use to upload the file. In your form code, you will need to specify the form type as "enctype = multipart/form-data". Specifying this form type allows you to send the request to upload the file. If you omit this line, the form will not function properly. Once the submit button has been pressed, we will then validate the file in queue to be uploaded.
The code below shows exactly what you will enter: The code above specifies the form type to be able to perform the upload. The action of the form will refresh to the same page via the post method, and the name of the form is stated.
Next, you can also use a hidden form element to specify the max file size of the intended file to upload. The size is specified in bytes like this: Listed below is a quick reference outlining file size:
8 bits = 1 byte
1024 bytes = 1 kilobyte
1024 kilobytes = 1 megabyte
1024 megabytes = 1 gigabyte
For uploading images, you should not be past the megabytes. Many digital cameras take high-resolution images that can be megabytes in file size, but you do not want 100's or 1,000's of users uploading images that are that large. The bandwidth and storage for your site could shrink rather quickly. However, enter in the appropriate value in byes that you would like to use for your site.
Now that you have the form type identified and a max file size specified, next you will need to put in the form element that allows the user to browse their HDD and select the file (image). See code below: Note: Initially, the user can select any file to upload of any size. It will be after they press the submit button that we begin filtering through the request.
Name entered here will be stored in the $_FILES array, so we will be looking for $_FILES['userfile'] when the submit button has been pressed. Input type = "file" is the code used to create the form element to browse your computer for a file to upload. The size specified is for the size of the form element, not the size of the file.
The final part of the form will be the submit button. Once clicked, we will begin determining if a file was selected to upload, and if it is a valid file to upload. The submit button is the same as any other form, nothing changes: Now that your form has been constructed, we can begin the script. Lets add the IF statement above the form, with the ELSE condition to display the form. Therefore, we will have a closing <? } ?> as the very last line of code. With this added, here is what your code will look like so far: Remember, the form code listed is just the essentials for it to work; you will build your design around this, or add the elements to an existing form you have.
Beginning the Script
Our first line of code is to determine if the submit button has been pressed. That is expressed by if(isset($_POST['submit'])) . From this point we begin to actually analyze the file selected to be uploaded. Step one is to determine if the user selected a file to be uploaded. Remember, all information about the image will be available in the $_FILES array. In our case, it is: $_FILES['userfile'] . To see all of the information or variables stored in $_FILES, you can use var_dump. If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none. So we will check if the user selected a file for upload by checking the size. See code below: The IF condition checks if the file size is greater than 1. If it is, then execution of the script continues. All other conditions will be placed inside this IF statement. If not, code would be executed un-necessarily, not to mention errors that will occur because a file was not selected to be uploaded.
For later use in the script, I elected to define some variables as the next part of the code. The variables are for file size, height and width. The variables are not required (where you could specify the value instead), however they are helpful if you would like to make adjustments, and only in one place.
Accessing the File
Getting information about the file uploaded is next. We will access the appropriate function, and store that data into a variable. The information we will request is file size. This is obtained from the getimagesize() function. PHP assigns a temporary name to the file which is how we access the file within the $_FILES array. The exact code we will use is shown below:
Check File Size (in bytes)
Now that we have accessed the file selected to be uploaded and obtained the size, the next step is to begin filtering the file through your limitations. The numerical limitations we specified above (size, height and width),. Before checking the height and width, lets first check that the file size is within the parameters set. If you recall, we set a maximum file size as a part of the form (MAX_FILE_SIZE), as well as the $max_size variable. We will check the size of the file against both of the variables specified to ensure that the file is within the specified limits. See code below for details: As you can see, the code checks if the uploaded file is greater than MAX_FILE_SIZE or greater than the $max_size variable. If it is, the condition will return TRUE, and the die() function will be executed that kills the script and displays the message within.
Check File Extension
The next part in the process of filtering the file selected for upload is to determine if the file carries an image extension. For this article, the code is written to only allow JPG or PNG files. Using the Explode() function, the name of the image (including the extension) is stored into an array. Explode splits the variable at the specified character. In the code, the variable is split at "." which precedes the extension. Next, the count() function checks to see how many elements are in the array, and then the last element of the array (which should be the extension name) is stored in the $ext variable. From this point, the extension has been derived from the file name, and the IF statement check to see if it is a JPG or PNG. See the full code below:
Check and Double Check File Type
Now that the file is within the size you deem appropriate to be uploaded, and carries an image extension, we will filter by file type to verify it is an image. Several methods exist for determining the type of file uploaded. 1.) We can check the type based on what the browser sent, or 2.) Check the MIME type from the GD Library getimagesize() function. This method requires the GD Library to be installed on the host server for your site. #2 would be the preferred method, since the file type determined by the browser can be faked. But in the case you do not have the GD Library installed, I will show the code to do both. In fact, it might not be a bad idea to just run both just to be safe.
The code below is to allow only JPG or PNG images. I believe older versions of Internet Explorer recognized JPG files as image/jpeg. But with the new version, like Firefox, IE recognizes JPG files as images/pjpeg. So you can check either or to be safe. As for PNG files, I believe image/png will work just fine, and image/x-png will also be recognized.
Check Image Size (Height and Width)
By reaching this point of the script, it can be assumed that an image was selected for upload, as it has passed through the conditions for extension name, file type and size. The last condition the image must pass is verification of height and width. To do this, the variables specified at the beginning of the script can be utilized, rather than specifying a static number. This way, if you change your mind, you can just change the value of the variable, instead of searching through the code to make multiple edits in possibly multiple locations.
Under the "Accessing the File" portion of this article, we stored size information about the uploaded file into the $info variable. The width of the file is stored in: $info, and height is stored in: $info. A simple condition allows us to compare these values vs. the variables specified. See the code below: As a part of error handling, if the user uploaded a file that is too large, take the time in the code to display to the user what size of file was uploaded, and what the limit constraints are. This allows the user to make the appropriate change to complete a successful upload on the next attempt.
Rename the Image and Store It
This is the heart of the script that all other segments of code has lead to. Before storing the file, you as the reader need to decide how you would like to name the file. Several options exist, but they are conditional to your intentions. If you plan on multiple users uploading multiple files then each image name must be unique. If a user will only upload one file, say for an AVATAR in the forums, then you can name the image as their username if you like and be done with it.
You do not want to allow the user to control the name of the file, and upload it directly to your site. This can cause problems, as the user can have a filename that includes something like: "../../" which could be potentially malicious or cause multiple complications with your database. So come up with a way you would like to name the file yourself.
The code in this article will be aimed towards a scenario where a user can upload multiple files. In this case, you can create an "images" table in your database with the following fields:
The $filename variable combines the username and new image number. Finally, the one line of code that performs the actual upload. From within an IF condition, the move_uploaded_file() function will take the uploaded file specified (must be valid, aka through HTTP POST) and move it to the specified destination. Of course, the comma (,) separates the two parameters.
As you can see in the destination part of the move_uploaded_file() function, you must use the absolute path to the file (document root). You can just specify a URL, that just doesn't make much sense. Also, remember $ext from the "Check File Extension" part of the article? We use it here to append to the filename.
Note:If the filename already exists, the existing image will be overwritten by the new image. This is why its important to use a unique naming system if you elect to upload multiple files for multiple users.
If the upload was a success, the condition will return TRUE and the "file uploaded successfully" line will be displayed. If not, the function will return FALSE, and the "error occurred while uploading" message will be displayed.
Conclusion and Debugging
No more code is required to upload a file from this point in the script. Any other coding is up to you for the other parts of your script or website. The first time I began constructing an image upload script, I found it quite useful to display the variables along the way for debugging. Particularly, displaying the array of information about image stored in the $_FILES array. You could use var_dump() to display everything, but its not visually friendly. Instead, here is the same information but broken up a bit to make it easier to read:
Here is all of the code for the script. Displaying the value of other variables as you progress through your script will also aid in any complications you encounter. As always, feel free to post any questions about the script or any other subject for that manner in the Forums for help. Thanks for reading, I hope you found value in the article and it will help you get set in the right direction.
-bs0d | AllSyntax.com
No Comments for this page.