使用 PHP 上传文件
在 PHP 中,上传文件的过程可以通过多种方法来实现。这是一个改进的 PHP 脚本,它结合了最佳实践并解决了您遇到的错误:
// Declare the target directory for uploaded files $target_dir = "uploads/"; // Initialize an empty array for allowed file types $allowedTypes = ['jpg', 'png']; // Check if the form has been submitted if (isset($_POST['submit'])) { // Retrieve the file details $target_file = $target_dir . basename($_FILES['fileToUpload']['name']); $file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); // Validate the file type if (!in_array($file_type, $allowedTypes)) { echo "Invalid file type. Only JPG and PNG files are allowed."; } // Check if the file already exists elseif (file_exists($target_file)) { echo "File already exists. Please choose a different file."; } // Check file size (assumes a 5MB limit) elseif ($_FILES['fileToUpload']['size'] > 5000000) { echo "File is too large. Maximum file size is 5MB."; } else { // Attempt to move the file to the target directory if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) { echo "File uploaded successfully!"; } else { echo "File upload failed. Please try again."; } } } ?>
此脚本提供了改进的错误处理和验证机制,确保仅上传允许的文件类型并防止重复或过大的文件被接受。
以上是如何使用PHP安全上传文件?的详细内容。更多信息请关注PHP中文网其他相关文章!