首页 >后端开发 >php教程 >如何在PHP中正确上传文件并处理潜在的错误?

如何在PHP中正确上传文件并处理潜在的错误?

Patricia Arquette
Patricia Arquette原创
2024-12-09 13:02:18568浏览

How to Correctly Upload Files in PHP and Handle Potential Errors?

使用 PHP 上传文件

将文件上传到指定文件夹是许多 Web 应用程序中的常见任务。本题探讨了一个简单的 PHP 代码块,旨在实现此任务。

$folder = "upload/";
if (is_uploaded_file($HTTP_POST_FILES['filename']['tmp_name'])) {   
    if (move_uploaded_file($HTTP_POST_FILES['filename']['tmp_name'], $folder . $HTTP_POST_FILES['filename']['name'])) {
         echo "File uploaded";
    } else {
         echo "File not moved to destination folder. Check permissions";
    };
} else {s
     echo "File is not uploaded";
}; 

但是,执行时出现错误:

Notice: Undefined variable: HTTP_POST_FILES in C:\wamp\www\sdg\import\ips.php on line 3

解决方案:

该错误是由于使用已弃用的变量 $HTTP_POST_FILES 引起的。相反,请使用 $_FILES:

$folder = "upload/";
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {   
    if (move_uploaded_file($_FILES['filename']['tmp_name'], $folder . $_FILES['filename']['name'])) {
         echo "File uploaded";
    } else {
         echo "File not moved to destination folder. Check permissions";
    };
} else {s
     echo "File is not uploaded";
}; 

增强型 PHP 代码:

以下增强型 PHP 代码提供了改进的功能,包括类型检查和文件大小验证:

$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 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.";
    } 
    // Move file
    elseif (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $msg = "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
    }
}
?>

HTML代码:

<form action="upload.php" method="post">

此改进的代码可确保仅上传允许的文件类型,防止重复的文件名,并限制文件大小以避免服务器过载。

以上是如何在PHP中正确上传文件并处理潜在的错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn