I have an upload form and am checking the file size and file type to limit the uploaded file to 2 megabytes and either .pdf, .jpg, .gif or .png file types. My goal is to have an alert message displayed to the user if they violate one of these rules.
There are four scenarios:
- Correct Size / Correct Type (working)
- Correct Size / INCORRECT Type (working)
- INCORRECT Size / Correct Type (not working)
- INCORRECT Size / INCORRECT Type (not working)
With my current code, it always displays the incorrect “type” message when the file size is greater than 2 megabytes (#4), even if the file type is correct (#3).
Any ideas why?
if (isset ( $_FILES['uploaded_file'] ) ) {
$file_size = $_FILES['uploaded_file']['size'];
$file_type = $_FILES['uploaded_file']['type'];
if (($file_size > 2097152)){
$message = 'File too large. File must be less than 2 megabytes.';
echo '<script type="text/javascript">alert("'.$message.'");</script>';
}
elseif (
($file_type != "application/pdf") &&
($file_type != "image/jpeg") &&
($file_type != "image/jpg") &&
($file_type != "image/gif") &&
($file_type != "image/png")
){
$message = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
echo '<script type="text/javascript">alert("'.$message.'");</script>';
}
else {
store_uploaded_file($id);
}
}
Something that your code doesn’t account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:
Look into the docs for
move_uploaded_file()(it’s called move not store) for more.