Want to upload file using PHP? use the below example code with HTML form and PHP code which require to upload any files. Apart from this, we have also shared How to check if file already exists and How to limit file type.
Read more
Create Create The HTML Form using below code:
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 copy paste 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)); // Check if image file is a actual image or fake image 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; } } ?> |
How to check if file already exists?
1 2 3 4 5 6 7 | <?php // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } ?> |
How to limit file type?
Use the following code if you want to limit the file type to upload.
1 2 3 4 5 6 7 | <?php // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.