w3resource

File upload in PHP

Description

In this page, we will discuss how file uploading is performed using PHP. For uploading files using PHP, we need to perform following tasks -

1. Set up an html page with a form using which we will upload the file.
2. Setup a PHP script to upload the file to the server as well as move the file to it's destination.
3. Inform the user whether the upload was successful or not.

Code :

<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" size="20" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<?php
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
?>

Explanation

Code  Explanation: $_FILES["uploaded_file"]["name"] The original name of the file uploaded from the user's machine. $_FILES["uploaded_file"]["type"] The MIME type of the uploaded file. You can use different types for test files, images and video. $_FILES["uploaded_file"]["size"] The size of the uploaded file in bytes. $_FILES["uploaded_file"]["tmp_name"] The location in which the file is temporarily stored on the server. $_FILES["uploaded_file"]["error"] An error code if  the file upload fails.

This way you can upload files to a web server. We encourage you to copy the codes above and try it on your computer or a web server.

Previous: PHP secure mail
Next: Cookies



PHP: Tips of the Day

Output a Multidimensional Array with index and value and print into the table

Example:

Array
(
 [0] => Array
 (
 [id] => 13
 [category_id] => 7
 [name] => Leaving Of Liverpool
 [description] => Leaving Of Liverpool
 [price] => 1.00
 [virtual] => 1
 [active] => 1
 [sort_order] => 13
 [created] => 2007-06-24 14:08:03
 [modified] => 2007-06-24 14:08:03
 [image] => NONE
 )
[1] => Array
 (
 [id] => 16
 [category_id] => 7
 [name] => Yellow Submarine
 [description] => Yellow Submarine
 [price] => 1.00
 [virtual] => 1
 [active] => 1
 [sort_order] => 16
 [created] => 2007-06-24 14:10:02
 [modified] => 2007-06-24 14:10:02
[image] => NONE
 )
)
<table>
<?php
foreach ($products as $key => $value) {
 foreach ($value as $k => $v) {
 echo "<tr>";
 echo "<td>$k</td>"; // Get index.
 echo "<td>$v</td>"; // Get value.
 echo "</tr>";
 }
}
?>
</table>