i am trying to match a image/type
of a file upload in PHP
for validation:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$data = [
// Other POST Variables
'uploadimageType' => $_FILES['uploadimage']['type']
];
if((strcmp($data['uploadimageType'],'image/jpeg')!=0) || (strcmp($data['uploadimageType'],'image/png')!=0) || (strcmp($data['uploadimageType'],'image/gif')!=0) ) {
echo 'Invalid Image format';
}else{
echo 'Valid';
}
?>
The HTML used for submit:
<form action="<?php echo URLROOT; ?>/users/upload" method="post" enctype="multipart/form-data">
<!-- Other Input Tags -->
<div class="form-group">
<label for="uploadimage">Upload Image <sup>*</sup></label>
<input type="file" name="uploadimage" class="form-control-file <?php echo (!empty($data['uploadimage_err'])) ? 'is-invalid' : ''; ?>">
<span class="invalid-feedback"><?php echo $data['uploadimage_err']; ?></span>
</div>
<!-- Submit Button -->
</form>
Now, the problem is that even if I try to upload an image(.jpg, .png, .gif) it shows Invalid Image Format . Is there anything that I am missing here because this seems to be very simple yet complicated. Any suggestions would help.
Try this
$allowed_mime_type_arr = array('image/gif','image/jpeg','image/pjpeg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['uploadimage']['name']);
if(in_array($mime, $allowed_mime_type_arr)){
echo 'Valid Image format';
}else{
echo 'Invalid Image format';
}
This will Works by Change if Condition.
$data = [
'uploadimageType' => 'image/jpeg'
];
if((strcmp($data['uploadimageType'],'image/jpeg')!=0) && (strcmp($data['uploadimageType'],'image/png')!=0) && (strcmp($data['uploadimageType'],'image/gif')!=0) ) {
echo 'Invalid Image format';
}
else {
echo 'Valid';
}
if($_SERVER['REQUEST_METHOD'] == "POST") {
$data = ['uploadimageType' => strtolower(pathinfo($_FILES['uploadimage']['name'],PATHINFO_EXTENSION))];
$ext = array("png","jpg","jpeg");
if(!in_array($data['uploadimageType'],$ext) ) {
echo 'Invalid Image format';
}else {
echo 'Valid';
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.