The code to upload file in PHP is very simple, but we need to understand the flow which is a below.
- Browse the file from a local system
- Upload to server
- Server keeps it on a temporary path
- Copy from temporary to permanent path
Create a file upload form
<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>
Note:
- An enctype attribute of the <form> tag has been specified. This attribute specifies which content-type to use when submitting the form
- We have used “multipart/form-data” to upload binary data, like the contents of a file, to be uploaded
- If proper enctype is not provided, upload will not work.
- File upload is a huge security risk so you must check what type of files are being uploade
Create a file upload script (upload-file.php)
<?php
$my_folder = “./uploads/”;
copy($_FILES["file"]["tmp_name"],$my_folder.$_FILES["file"]["name"]);
echo “File uploaded.”;
?>
This will upload the file to the specified path.
Note:
- The default file upload size using a browser is usually 2MB so files larger than this size may not upload. You will have to alter the file upload setting on the server.
- You need to set write permission to the folder where file needs to be upload. In our case, the “uploads” folder needs to have a 777 permission on a linux/unix server.