Uploading files to the server
We can upload files to the remote server using PHP.
1. Upload form
Here is an example:
<form action= "Upload.php" method="post" enctype="multipart/form-data">
<table>
<tr><td>
<input name="user_file" type="file" id="user_file">
</td> </tr>
<tr><td>
<input name="upload" type="submit" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
The enctype attribute of the <form> tag specifies which
content-type to upload.
"multipart/form-data" is used when a form requires binary data.
The type="file" attribute of the <input> related to a a
file leads to a a browse-button.
2. Upload.php script
The code to upload a file contains the following
PHP $_FILES array:
$_FILES["file"]["name"] : the name of the file to upload
$_FILES["file"]["type"] : the type of the file to upload
$_FILES["file"]["size"] : the size in bytes of file to upload
$_FILES["file"]["tmp_name"] : the name of the temporary copy of the file
$_FILES["file"]["error"] : the error code from the file upload
3. Saving the Uploaded file
The uploaded file is a temporary copy in the PHP temp
folder on the server. It disappears when the script
ends. To store the uploaded file we need to copy it
to a different location, like the Upload directory.
the related script is:
move_uploaded_file($_FILES["file"]["tmp_name"],
"Upload/" . $_FILES["userfile"]["name"]);
4. Downloading file
The main script is:
<?php
header("Content-Disposition: attachment; filename=$name_of_file");
?>
5. Example:
<form action= "Upload.php" method="post"
enctype="multipart/form-data">
<table>
<tr><td><input name="file" type="file"
id="file"></td></tr>
<tr><td><input name="upload" type="submit"
id="upload" value=" Upload "></td></tr>
</table>
</form>
<?php
if(isset($_POST['upload']) && $_FILES['file']['size'] > 0)
{
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
//Store the fille:
move_uploaded_file($_FILES["userfile"]["tmp_name"],
"Upload/" . $_FILES["userfile"]["name"]);
//Check if everything is ok:
echo "Stored in: " . "Upload/" . $_FILES["userfile"]["name"];
echo "<br>File $fileName uploaded<br>";
}
?>
|