感谢您有机会提问。我已经广泛搜索了答案,但我找不到它。我希望你们能够提供一些关于为什么会出现这个问题的见解。
谜题:我已经设置了一个表单来上传文档,以便我的网站访问者可以提交文章供审阅。该表单用于正确处理指定的所有文件扩展名,docx,.txt,PDF等。但是,如果有人试图上传除.txt之外的任何其他格式,表单会显示错误消息(奇怪的是,这些工作正常)。我检查了主机提供商,错误日志中没有记录任何内容。
以下是相关的相关代码:
function saveUploadedFile() {
$allowedExts = array("pdf", "txt", "doc", "docx", "dot");
$extension = end(explode(".", $_FILES["cFile"]["name"]));
if ( (($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["cFile"]["type"] == "application/plain")
|| ($_FILES["cFile"]["type"] == "text/plain")
|| ($_FILES["cFile"]["type"] == "application/msword"))
&& in_array($extension, $allowedExts)) {
if ($_FILES["cFile"]["error"] > 0) {
return '';
} else {
$fileName = $_FILES["cFile"]["name"];
return $fileName;
}
}
return '';
}
// Write for us form
else if (isset($_FILES['cFile']['name'])) {
if ((isset($_POST['cName']) && !empty($_POST['cName']))
&& (isset($_POST['cEmail']) && !empty($_POST['cEmail']) && isValidEmail($_POST['cEmail']))
&& (isset($_POST['cMessage']) && !empty($_POST['cMessage']))
&& !empty($_FILES['cFile']['name'])) {
$cName = $_POST['cName'];
$cEmail = $_POST['cEmail'];
$cMessage = $_POST['cMessage'];
$fileName = saveUploadedFile();
if ($fileName != '') {
$to = 'contact@REMOVED.com';
$subject = 'Article';
$msg = 'Author: ' . $cName . "\n" . 'Message: ' . $cMessage;
$fileSize = $_FILES['cFile']['size'];
$handle = fopen($_FILES['cFile']['tmp_name'], 'r');
$content = fread($handle, $fileSize);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$headers = "From: " . $cName . " <" . $cEmail . ">
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=\"" . $uid . "\"
This is a multi-part message in MIME format.
--" . $uid . "
Content-Type: application/octet-stream; name=\"" . $fileName . "\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=\"" . $fileName . "\"
" . $content . "
--" . $uid . "
Content-type:text/plain; charset=iso-8859-1
" . $msg . "
--" . $uid . "--";
if (!@mail($to, $subject, $msg, $headers)) {
echo '<p class="failed validation">The e-mail could not be sent. Please try again later</p>';
} else {
echo '<p class="success validation">Your message has been sent</p>';
}
} else {
echo '<p class="failed validation">Your file could not be uploaded. Please make sure that you attached one of the following types of files: a plain text file, a MS Word document, a PDF file or a zip file</p>';
}
} else {
echo '<p class="failed validation">Your file could not be uploaded. Please make sure you have completed all required fields and that you have provided a valid email address.</p>';
}
}
这是出现的错误消息:“您的文件无法上传。请确保您附加了以下类型的文件之一:纯文本文件,MS Word文档,PDF文件或zip文件“
为什么这段代码会接受.txt文件但不接受.docx或PDF?
谢谢!
答案 0 :(得分:0)
我在某处读到[“类型”]效果不好的地方。我建议删除该部分代码。
答案 1 :(得分:0)
我认为您应该按如下方式编辑代码:
if (in_array($extension, $allowedExts)) {
if ($_FILES["cFile"]["error"] > 0) {
return '';
} else {
$fileName = $_FILES["cFile"]["name"];
return $fileName;
}
}