File Uploading with PHP
This guide demonstrates how to upload files in PHP, addressing a common error encountered in previous approaches.
Problem:
When attempting to upload a file to a specified folder, an error arises due to the use of the deprecated HTTP_POST_FILES variable.
Solution:
The following PHP code provides a modernized and updated solution for file uploading:
$target_dir = "upload/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); $allowedTypes = ['jpg', 'png']; if (isset($_POST["submit"])) { // Check file type if (!in_array($imageFileType, $allowedTypes)) { $msg = "Type is not allowed"; } // Check if file already exists elseif (file_exists($target_file)) { $msg = "Sorry, file already exists."; } // Check file size elseif ($_FILES["fileToUpload"]["size"] > 5000000) { $msg = "Sorry, your file is too large."; } elseif (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { $msg = "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded."; } }
Explanation:
HTML Code for Uploading:
<form action="upload.php" method="post">
Using this updated code, you can successfully upload files to your desired folder and handle validation errors appropriately.
The above is the detailed content of How to Solve File Upload Issues in PHP Using $_FILES?. For more information, please follow other related articles on the PHP Chinese website!