Thread: PHP File Upload
View Single Post
  #1  
Old 05-04-2009, 05:14 PM
welcomewiki welcomewiki is online now
Member
 
Join Date: Dec 2008
Location: India
Posts: 80,534
Default PHP File Upload

With PHP, it is possible to upload files to the server.



Create an Upload-File Form


To allow users to upload files from a form can be very useful.
Look at the following HTML form for uploading files:





enctype="multipart/form-data">










Notice the following about the HTML form above:
  • The enctype attribute of the
    tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded
  • The type="file" attribute of the tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-****on next to the input field

Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads.




Create The Upload Script

The "upload_file.php" file contains the code for uploading a file:


if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "
";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "
";
echo "Type: " . $_FILES["file"]["type"] . "
";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>



By using the global PHP $_FILES array you can upload files from a client computer to the remote server.


The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:


  • $_FILES["file"]["name"] - the name of the uploaded file
  • $_FILES["file"]["type"] - the type of the uploaded file
  • $_FILES["file"]["size"] - the size in bytes of the uploaded file
  • $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
  • $_FILES["file"]["error"] - the error code resulting from the file upload
This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.

Reply With Quote