If we have created a form to receive a file, the next part is to create a PHP script to process the data. For the sake of simplicity and clarity, I'll keep this script as a separate file, called uploader.php. Start that page with a simple script in the body, upload the page, and test the form by uploading a file and pressing submit:

<?php $upload_tmp_dir = “/tmp”;
print_r ($_FILES['upload']); ?>

The first variable we set, $upload_tmp_dir, is a little bit of a hack. In most cases, PHP should recognize that it has a tmp folder, where uploaded and cached files are temporarily stored. However, installations of PHP and Apache on Windows tend to get a little confused, and we must “remind” it that the directory exists. If your server does not run on Windows, this reminder does no harm. (We will be looking at the tmp folder in a moment).

The details of any uploaded file are held in a system variable called $_FILES, addressed by the value of the name attribute associated with the file input in the original form. After you attempt to upload the file via the form, you’ll see that the array has a number of parts: it contains the file type, any error associated with the file upload, the temporary name and location of the file, etc. We'll be using some of this information next.

If we want to bypass any interrogation of the file and trust it implicitly – which we should never do – we can move the file into our images folder directly. First, we need to specify where the file will go by appending the $uploadedfile variable to the directory we wish to store it in our website. In this case, I will use the images directory:

$uploadedfile = "images/{$_FILES['upload']['name']}";

Note that the braces around the $_FILES variable is simply a way of concatenating the images directory with the file name: it could also be written as follows:

$uploadedfile = "images/".$_FILES['upload']['name'];

Then, to move the file from our tmp directory, we'll use an if statement:

if (move_uploaded_file ($_FILES['upload'] ['tmp_name'], $uploadedfile )) {
	echo "File successfully uploaded";
} else {
	echo "Failure to upload";
}

There are many tests we could and should do to the file in order to determine if it is the kind we want: we should be double-checking the file size; checking that the name of the file does not have the same name as a file already present in the destination folder, since PHP will overwrite any such file; and checking the file type. We'll do those tests in the next article in this series.