Friday 15 March 2013

[PHP] Uploading A File

This tutorial is aimed at beginners. It uses basic functions so you shouldn't have any difficulty. The purpose of the tutorial is to teach you how to upload files using PHP and HTML forms.
The following requirements should be met before starting this tutorial: HTML & PHP Knowledge PHP-enabled host Ability to upload

-------------------------------------------------------------------------------------------------------------------------------------
 To simplify the process this tutorial will be divided into steps, beginning with the creation of the upload form.

STEP 1
 Create a new HTML file and add the following code snippet:




The enctype attribute of the form defines the type of content we are working with. By using multipart/form-data for this attribute we are able to work with binary data (which we will need for the file to be uploaded).

In the first input tag you notice the following attribute: file. This allows us to process a file for input. That way, the user can select the file they wish to send.

The action attribute of the form is: "fileUpload.php". That is the file that will be processed when this form is submitted (when the "Upload" button is clicked).

STEP 2
The next step involves creating the upload script. Create a PHP file and call it: fileUpload.php. Note that you do not have to give it this name, but it must match the name in our HTML document's form action.

Add the following code snippet in your PHP file:




move_uploaded_file(...) is required because our file is uploaded to a temporary location. Once the script ends, it will be deleted. By using move_uploaded_file(...) we move it to a permanent location relative to the file's name.

STEP 3
We can do some modifications to our upload script like setting file type and size restrictions. To do this we'll be comparing the following superglobals with certain values:
_$FILES["file"]["type"]
_$FILES["file"]["size"]

Here is a small snippet that demonstrates how to check if the file is a gif file.


This snippet checks if the file size exceeds 1 megabyte:


Resource Program Here

0 comments:

Post a Comment