Q:
Explain how to store the uploaded file to the final location.
Answer
A HTML form should be build before uploading the file. The following HTML code is used for selecting the file that is to be uploaded. The type attribute of input must be “file”.
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
At the time of executing uploader.php, the uploaded file will be stored in a temporary storage are on the webserver. An associative array $_FILES['uploadedfile']['name'] is used for uploading. The ‘name’ is the original file that is to be uploaded. Another associative array $_FILES['uploadedfile']['tmp_name'] is used for placing the uploaded file in a temporary location on the server and the file should be empty and should exist with the tmp_name.
The following code snippet is used for uploading the file.
$target_path = "uploads/"; // the target location of the file
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
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 while uploading the file”;
}
The function move_uploaded_file()is used to place the source file into the destination folder, which resides on the server.
If the uploading is successful, the message “The file filename has been uploaded. Otherwise the error message “There was an error while uploading the file” would be displayed.
View answer
Workspace
Report Error
Discuss