In this tutorial, I am going to share how to upload the file using the PHP programming language.
Create the index.html file and copy paste below code to create a form to upload the file. Please make sure you have added enctype="multipart/form-data"
in form.
1 2 3 4 5 6 7 8 9 10 11 12 | <!DOCTYPE html> <html> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> </body> </html> |
Create “upload.php” file and add the below PHP code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } ?> |
If you want to add the condition to check the file size, then use the below code.
1 2 3 4 | if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.