I write php code to allow user to submit image and upload it to the server. I get it working and the server receives the image. But it seems like the server is accepting even .avi and .flv files. I do write if/else statement for checking whether a file is an image, but why it doesn’t work? Thank you
This is my php code
$tmpPath = $_FILES["image"]["tmp_name"];
$movedPath = "submit-img/" . $_POST["category"] . "/" . $_FILES["image"]["name"];
$fullURL = parse_url($_SERVER['HTTP_REFERER']);
$query = explode("&", $fullURL["query"]); //only choose first query
$prevPage = "gallery.php" . "?" . $query[0];
//I get the file type here
$fileType = strpos($_FILES["image"]["type"], "image/");
//if its not an image then redirect to the previous page and send a message
if ($fileType === false || ($_FILES["image"]["size"]) == 0 || $_FILES["image"]["size"]/1024 > 5000){
$prevPage = $prevPage . "&imgSubmit=none#imgSubmitForm";
header("Location: " . $prevPage);
}else if ($_FILES["image"]["size"] > 0){ //if file is an image
if (!is_file($movedPath)){
move_uploaded_file($tmpPath, $movedPath);
}else{
while (is_file($movedPath)){
$extension = strrchr($movedPath, ".");
$movedPath = str_replace($extension, "", $movedPath) . "1" . $extension;
}
move_uploaded_file($tmpPath, $movedPath);
}
$prevPage = $prevPage . "&imgSubmit=submitted#imgSubmitForm";
header("Location: " . $prevPage);
}
The comment on this line is fundamentally misleading. The
sizekey in$_FILESis the size of the file in bytes; it has nothing to do with whether the “file is an image”. (In particular, it is not the physical size of the image.)If you need to test whether a file is an image, your best bet is to use the
getimagesizefunction. This function will return the size of an image if it’s an image type that PHP recognizes, or zero if it doesn’t appear to be an image.Do not use the
typefield of the$_FILESarray to determine whether a file is an image. This field is populated by the browser, not by the server, and may contain misleading and/or flat-out incorrect information.