我正在一个网站上工作,这个页面有一个表单提交,包括文件上传,表单从 html 到 php 再到 mysql 没有问题,但文件上传似乎不想处理。
HTML(在要提交的表单内):
Document: <input type="file" name="fileToUpload" required></br></br>
PHP(不启动mysql):
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($FileType != "doc" && $FileType != "docx" && $FileType != "pdf") {
echo "Sorry, only DOC, DOCX, & PDF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
错误要么出现在文件类型上,要么出现在底部。我在服务器上的任何地方都找不到 php.ini。
感谢您的宝贵时间,我应该制作一个 php.ini 吗?
编辑:这是 print_r($_FILES);
最佳答案
这样的事情怎么样?这是未经测试的,我只是取出你的文件类型检查并使用数组替换它。
<?php
$target_dir = "uploads/";
$allowed_types =array('doc','docx','pdf')
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$error = null;
// Get the file extension
$ext = pathinfo($target_file, PATHINFO_EXTENSION);
// Search the array for the allowed file type
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if (in_array($ext, $allowed_types, false) != true) {
$error = "Sorry, there was an error uploading your file.";
return $error; // or use exit;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been
uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
关于PHP 文件上传无法正常使用,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54699078/