Uploading a file in PHP

To upload a file two form elements are needed. The form needs an attribute specifying that the form will contain a file input field and a file form element is needed to allow the user to select a file to upload.

<form action="#" method="post" enctype="multipart/form-data">
	<input type="file" name="upload" id="upload" />
	<input type="submit" name="submit" id="submit" value="Submit" />
</form>

This simple form has a file form element and a submit button. Note the attribute enctype attached to the form.

if(isset($_POST['submit']))
{
	$dir = getcwd().'/';
	$filename = $dir.basename($_FILES['upload']['name']);
	if (move_uploaded_file($_FILES['upload']['tmp_name'], $filename))
		echo 'File uploaded.';
	else
		echo 'An error has occurred.';
}

When a file is uploaded details of the file are stored in the $_FILES global variable. We use this variable to get the filename and check that it has been successfully uploaded. The $dir variable is the location that the file will be uploaded. This example uses the getcwd function to get the current directory the this code is in and upload the images in the same directory.

To upload multiple files you simply need in have more than one file form element. If you keep the name of the file element the same then you can loop through all the entries rather than referring to each field individually by name.

<form action="#" method="post" enctype="multipart/form-data">
	<input type="file" name="upload[]" />
	<input type="file" name="upload[]" />
	<input type="submit" name="submit" id="submit" value="Submit" />
</form>

The form has two file inputs and a submit button. The name upload[] specifies that when we process the posted data it should be an array of all the fields with the same name.

if(isset($_POST['submit']))
{
	$files = array('image/gif');
	$dir = getcwd().'/';

Again we check that the submit button has been pressed before we process the rest of the form. In this example we will specify a list of file types that we will allow for upload.

for($i = 0;$i < count($_FILES['upload']['name']); $i++)

The array that was created earlier is now looped over and we check that the file does not exceed a certain limit and that it has the file type specified earlier.

$filename = $dir.basename($_FILES['upload']['name'][$i]);
if ($_FILES['upload']['size'][$i] <= 2000 && 
    in_array($_FILES['upload']['size'][$i], $files) && 
    move_uploaded_file($_FILES['upload']['tmp_name'][$i], $filename))
	echo 'File uploaded.';
else
	echo 'An error has occurred.';

If the conditional statement evaluates to true then the file has been uploaded and a message is printed to the user.

Downloads

GitHub repository

Categories

Tags

No tags

Social