Upload files using PHP
PHP is “kind” with us when it comes to sending something to the server; being able to upload files it is not big deal. To upload a file means you can copy files from a client computer to the remote server. To handle the files, PHP offers the $_FILES array. This array will contain all the uploaded file information. We will use $_FILES[”field_name”][”options”] where the first parameter is the field name into your form and the second index can be: “name”, “type”, “size”, “tmp_name” or “error”. Just look at this table to figure out what they mean.
| Array | Description |
|---|---|
| $_FILES[”file”][”name”] | Returns the actual file name |
| $_FILES[”file”][”type”] | Get the type of the file |
| $_FILES[”file”][”size”] | Get the size of the file (bytes) |
| $_FILES[”file”][”tmp_name”] | The temporal name for the uploaded file on the server |
| $_FILES[”file”][”error”] | Error code resulting from the upload |
In your script you can use for example $_FILES[’file’][’size’] variable to throw away any files that are either too small or too big, the $_FILES[’file’][’type’] variable to files that didn’t match a certain type criteria . As of PHP 4.2.0, you could use $_FILES[’file’][’error’] which return the error code associated with this file upload.
Basicly how do upload works?
Well it’s easy. You have a form that has a field of “file” type
<input type="file" name="myfile" />
The form submits its contents via POST to an action which is a PHP file that can contain what’s below. Very important for your uploads to work is creating a specific type of <form> : a form that has enctype="application/x-www-form-urlencoded" . If you forget this the upload won’t work.
Lets have an example:
HTML contents :
<form enctype="application/x-www-form-urlencoded" action="script.php" method="post"> <input type="file" name="myfile" /> <input type="submit" name="submit" value="Upload" /> </form>
PHP contents:
<?php/* File name is null */
if($_FILES[’file’][’name’]==’’){
/* the path to the directory for upload*/
$target_path =’null’;die();
}
else{
$target_path = "FileDirectory/";
/* wrong file type - not a doc type file*/
if (substr($_FILES[’myfile’][’name’],strlen($_FILES[’myfile’][’name’])-4,4)!=’.doc’){
echo "Failed upload!";}
/* the path where file will be put */
$target_path = 'path_here' ;
if (!move_uploaded_file($_FILES[’myfile’][’tmp_name’], $target_path)){
/* error during upload */
echo "Error!";die ();
}
}
?>

RSS/XML