提问人:Alexander Fleming 提问时间:11/18/2023 最后编辑:Alexander Fleming 更新时间:11/18/2023 访问量:77
PHP 文件上传问题 - “move_uploaded_files”未按预期工作 [已关闭]
Issue with PHP file upload - "move_uploaded_files" not working as expected [closed]
问:
我目前正在为我的 PHP 应用程序开发文件上传功能,并且遇到了 move_uploaded_file 函数的问题。这是我的代码的简化版本:
<?php
$targetDirectory = "uploads/";
$targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_files($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "File uploaded successfully!";
} else {
echo "Error uploading file.";
}
?>
尽管为“uploads”目录设置了正确的权限,但文件似乎没有移动到那里。我已经检查了 $_FILES 数组,它包含预期的信息。可能导致此问题的原因是什么,我该如何排查和解决它?
其他信息:
- 我使用的是PHP 7.4。
- “uploads”目录具有必要的写入权限。
- 我正在本地开发服务器上对此进行测试。
任何帮助或见解将不胜感激!
答:
2赞
Ishtiaq Ahmed
11/18/2023
#1
您的代码中有一个小错别字。函数名称应为 move_uploaded_file(单数“文件”),而不是move_uploaded_files(复数“文件”)。下面是更正后的代码:
<?php
$targetDirectory = "uploads/";
$targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "File uploaded successfully!";
} else {
echo "Error uploading file.";
}
?>
评论
4赞
ADyson
11/18/2023
@AlexanderFleming像这样的错误应该产生 php 警告。确保已打开错误和警告日志记录,以便可以在日志文件中查找问题
0赞
mickmackusa
11/21/2023
请不要回答错别字的问题 - 只需投票将它们关闭为题外话:错别字。
2赞
Alexander Fleming
11/18/2023
#2
我找到了另一个代码
<?php
$targetDirectory = "uploads/";
// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Check if there was no error during file upload
if ($_FILES["fileToUpload"]["error"] == UPLOAD_ERR_OK) {
$targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]);
// Check if the file is of the expected type and size
$allowedTypes = ["jpg", "jpeg", "png", "gif"]; // Add more if needed
$fileExtension = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
if (in_array($fileExtension, $allowedTypes) && $_FILES["fileToUpload"]["size"] <= 5000000) { // Adjust size limit as needed
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "File uploaded successfully!";
} else {
echo "Error uploading file.";
}
} else {
echo "Invalid file type or size.";
}
} else {
echo "Error during file upload: " . $_FILES["fileToUpload"]["error"];
}
}
?>
评论
1赞
Ishtiaq Ahmed
11/18/2023
我认为它更好,因为它涵盖了上传大小限制、正确的编码类型、文件输入名称匹配和安全问题
评论