PHP File Upload
With
PHP, it is possible to upload files to the server.
A
very useful aspect of PHP is its ability to manage file uploads to your server.
Allowing users to upload a file to your server opens a whole can of worms, so
please be careful when enabling file uploads.
When
the uploader.php file is executed, the uploaded file exists in a temporary
storage area on the server. If the file is not moved to a different location it
will be destroyed! To save our precious file we are going to need to make use
of the $_FILES associative array.
The
$_FILES array is where PHP stores all the information about files. There are
two elements of this array that we will need to understand for this example.
·
uploadedfile - uploadedfile is the reference we assigned in our HTML
form. We will need this to tell the $_FILES array which file we want to play
around with.
·
$_FILES['uploadedfile']['name'] - name contains the original path of the
user uploaded file.
·
$_FILES['uploadedfile']['tmp_name'] - tmp_name contains the path to the
temporary file that resides on the server. The file should exist on the server
in a temporary directory with a temporary name.
Now
we can finally start to write a basic PHP upload manager script! Here is how we
would get the temporary file name, choose a permanent name, and choose a place
to store the file.
If
the upload is successful, then you will see the text "The file filename
has been uploaded".
This
is because move_uploaded_file returns true if the file was moved, and false if
it had a problem.
If
there was a problem then the error message "There was an error uploading
the file, please try again!" would be displayed.
Example:
<html>
<body>
<form
action="upload_file.php" method="post"
enctype="multipart/form-data">
<label
for="file">Filename:</label>
<input
type="file" name="file" id="file"><br>
<input
type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Upload_file.php
<?php
if
($_FILES["file"]["error"] > 0)
{
echo "Error: " .
$_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " .
$_FILES["file"]["name"] . "<br>";
echo "Type: " .
$_FILES["file"]["type"] . "<br>";
echo "Size: " .
($_FILES["file"]["size"] / 1024) . "
kB<br>";
echo "Stored in: " .
$_FILES["file"]["tmp_name"];
}
?>
0 comments:
Post a Comment