Sunday, May 23, 2010

Simplest File Upload in PHP

In many websites, we need to upload files like: our CVs in different job sites, our profile pictures in different social sites etc. It's very useful, and sometimes it has certain restrictions too.. like: you can upload a picture having maximum upper bound of 25MB size etc. Using php scripts, file uploading can be done easily through the following few steps.


Create an Upload-File Form using plain HTML 

(click here to view the code)



Create The Upload Script using PHP 

(click here to view the code)




By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:
  • $_FILES["file"]["name"] - the name of the uploaded file
  • $_FILES["file"]["type"] - the type of the uploaded file
  • $_FILES["file"]["size"] - the size in bytes of the uploaded file
  • $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
  • $_FILES["file"]["error"] - the error code resulting from the file upload
This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.

Restrictions on Upload 

In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be < 20 KB











Saving the Uploaded File 

(click here to view the code)

The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location.


No comments:

Post a Comment