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



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php/file-upload/file-upload-in-php.php