如果Or Statement不能正常使用PHP

时间:2015-02-28 15:03:06

标签: php if-statement

我正在建立一个可以上传文件的网站。我只想让人们上传Word,Powerpoint,Excel,PDF和JPG文件。因此,我做了这个if语句:

$target_dir = "files/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$filename = basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file selected
if (!isset($_FILES['fileToUpload']) || $_FILES['fileToUpload']['error'] == UPLOAD_ERR_NO_FILE) {
    $msg = "No file selected. Try again.";
    $uploadOk = 0;

} elseif (file_exists($target_file)) { // does file already exist?
    $msg = "File already exists.";
    $uploadOk = 0;

} elseif ($_FILES["fileToUpload"]["size"] > 10485760) { // filesize
    $msg = "File too huge.";
    $uploadOk = 0;

// THE PROBLEM IS IN THE FOLLOWING STATEMENT

} elseif ($fileType != "jpg" || $fileType != "doc" || $fileType != "docx" || $fileType != "ppt" || $fileType != "pptx" || $fileType != "xls" || $fileType != "xlsx" || $fileType != "pdf") {
    $msg = "Filetype not allowed";
    $uploadOk = 0;
}

if ($uploadOk != 0) {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $msg = "File uploaded.";
    } else {
        $msg = "File not uploaded.";
    }

但是,当我上传JPG,PDF,PHP或其他内容时,它总是会出错:不允许使用Filetype。我做错了什么?

3 个答案:

答案 0 :(得分:1)

$fileType != "jpg" || $fileType != "doc" || $fileType != "docx" || $fileType != "ppt" || $fileType != "pptx" || $fileType != "xls" || $fileType != "xlsx" || $fileType != "pdf"始终为true。您需要&&运算符而不是||

答案 1 :(得分:1)

不要让你的条件太复杂,只需使用in_array(),就像这样:

} elseif (!in_array($fileType, array("jpg", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "pdf"))) {
    $msg = "Filetype not allowed";
    $uploadOk = 0;
}

答案 2 :(得分:0)

您必须使用&&

} elseif ($fileType != "jpg" && $fileType != "doc" && $fileType != "docx" && $fileType != "ppt" && $fileType != "pptx" && $fileType != "xls" && $fileType != "xlsx" && $fileType != "pdf") {