Web Development
Using PHP

Follow on
Twitter

Uploading Files

See:
The 'file' type of form input field.
The MAX_FILE_SIZE hidden input field for PHP uploads.
Multi-part and other PHP file upload considerations.

<!DOCTYPE html>

<html>
<head>
  <title>Upload Document Example</title>
</head>

<body>
  <!-- Multi-part form. Part of the form will be the form data
  part will be the file. -->
  <form enctype="multipart/form-data" action="upload_process.php" method="post">
    <!-- Note: Users can easily over-ride the value for max file size. 
    Don't depend on this. 
    For PHP this must proceed a 'file' upload type.
    -->
    <input type="hidden" name="MAX_FILE_SIZE" value="100000"> Select file to upload:
    <input type="file" name="uploadedfile" ><br>
    <input type="submit" value="Upload File">
  </form>
</body>
</html>
<html><body><pre>
<?php
/*
PHP automatically uploads the files into a temporary
directory. If you want to keep the file you need to
move it to a new home.

This is the directory where the file will be moved.
It needs to already exist. In this case, inside the php
folder. The web server process also needs permission to
write to the folder.

The folder should have a limit separate from the entire
computer. If someone uploads many large files, you want
the directory to fill, but not the entire drive on the
computer which would cause the entire website to fail.
*/

$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension"

$_FILES is a built-in array that holds info about files.
'uploadedfile' comes from the name of the field in our form.
'name' is a built-in key for the file that contains
the original file name path.

In my experience, it does not usually have the whole path,
but it could. So we strip the path into off and just
get the name with the built in php function 'basename'
*/
$target_path = $target_path.basename( $_FILES['uploadedfile']['name']);

if ($_FILES["uploadedfile"]["error"] > 0)
{
  if ($_FILES["uploadedfile"]["error"] == 2)
	echo "Uploaded file was too large.<br />";
  else
    echo "Error: " . $_FILES["uploadedfile"]["error"] . "<br />";
}
else
{
  echo "Upload:    " . $_FILES["uploadedfile"]["name"] . "<br />";
  echo "Type:      " . $_FILES["uploadedfile"]["type"] . "<br />";
  echo "Size:      " . ($_FILES["uploadedfile"]["size"] / 1024) . " Kb<br />";
  echo "Stored in: " . $_FILES["uploadedfile"]["tmp_name"] . "<br />";
}
  

/* move_uploaded_file is a built-in php function. */
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
  echo "The file ".basename( $_FILES['uploadedfile']['name'])." has been uploaded";
} else{
  echo "There was an error uploading the file, please try again!";
}
?>
</pre></body></html>

Try it out: [link]

You are not logged in. Log in here and track your progress.