Monday, February 1, 2010

Uploading Files With PHP

The process of uploading a file has two dimensions. First, the HTML form must be displayed with the proper code to allow for uploads. Then, upon submission of the form, your PHP script must copy the uploaded file to its final destination.

However, for this process to work, a few things must be in place:
-PHP must run with the right settings
-A temporary storage directory must exist with the correct permissions
-The final storage directory must exist with the correct permissions.

There are several settings in the PHP configuration file(php.ini) that dictate file uploads. In the file uploads section of this file, you will see the following three lines:
file_uploads=On
;upload_tmp_dir =
upload_max_filesize = 2M
The first line dictates whether or not uploads are allowed. The second line states where the uploaded files should be temporarily stored. On most systems, this setting can be left commented out. On Windows, you would create a temporary directory, set to a value such as C:\temp, making sure the line is not preceded by a semicolon.

Finally, a maximum upload file size is set. The "M" is shorthand for megabytes in configuration settings. Save the php.ini file and restart your Web server. You can confirm the settings by running the phpinfo()script.

Next prepare your HTML upload form:
<html>
<head>
<title>File Upload Form</title>
</head>
<body>
This form allows you to upload a file to the server.<br>
<form enctype="multipart/form-data" action="upload.php" method="post">
Please choose a file: <input type="file" name="uploaded" /><br />
<input type="submit" value="Upload" />
</form>
</body>
</html>
And a PHP script which receives the HTML form is depicted below:
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'],$target))
{
echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
Hope this helps someone out there!

No comments:

Post a Comment

Get your own Widget