I am making a site where you can upload files. I just want people to upload Word, Powerpoint, Excel, PDF and JPG files. Therefore, I made this if-statement:
$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.";
}
However, when I upload a JPG,PDF,PHP or whatever, it always gives the error : Filetype not allowed. What am I doing wrong?
$fileType != "jpg" || $fileType != "doc" || $fileType != "docx" || $fileType != "ppt" || $fileType != "pptx" || $fileType != "xls" || $fileType != "xlsx" || $fileType != "pdf"
will always be true
. You want the &&
operator instead of ||
.
You have to use &&
} elseif ($fileType != "jpg" && $fileType != "doc" && $fileType != "docx" && $fileType != "ppt" && $fileType != "pptx" && $fileType != "xls" && $fileType != "xlsx" && $fileType != "pdf") {
Don't make your conditions too complicated, just use in_array()
, like this:
} elseif (!in_array($fileType, array("jpg", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "pdf"))) {
$msg = "Filetype not allowed";
$uploadOk = 0;
}