I have a form to upload image like below
<form name="sample" enctype="multipart/form-data" action="index.php" method="post" >
<input type="hidden" name="MAX_FILE_SIZE" value="2048000" />
Select an Image: <input name="photo" id="photo" type="file" /> <input type="submit" value="Upload" />
</form>
Now i have to check something like below ..
If(any file/image selected){
i will check here whether the selected file is a valid image.
}
I have managed the validation part for if but what i can not check is whether any file is selected or not.
I used the following condition
if(!empty($_FILES))
But this execute in all cased whether someone select a file or not.
Please someone help me how can i make this work.
Here is my full PHP code:
<?php
// Do not show notice errors
error_reporting (E_ALL ^ E_NOTICE);
if(!empty($_FILES)) // Has the image been uploaded?
{
include 'config.php';
$file = $_FILES['image_file'];
$file_name = $file['name'];
$error = ''; // Empty
// Get File Extension (if any)
$ext = strtolower(substr(strrchr($file_name, "."), 1));
// Check for a correct extension. The image file hasn't an extension? Add one
if($validation_type == 1)
{
$file_info = getimagesize($_FILES['image_file']['tmp_name']);
if(empty($file_info)) // No Image?
{
$error .= "The uploaded file doesn't seem to be an image.";
}
else // An Image?
{
$file_mime = $file_info['mime'];
if($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2')
{
$extension = $ext;
}
else
{
$extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime];
}
if(!$extension)
{
$extension = '';
$file_name = str_replace('.', '', $file_name);
}
}
}
else if($validation_type == 2)
{
if(!in_array($ext, $image_extensions_allowed))
{
$exts = implode(', ',$image_extensions_allowed);
$error .= "You must upload a file with one of the following extensions: ".$exts;
}
$extension = $ext;
}
if($error == "") // No errors were found?
{
$new_file_name = strtolower($file_name);
$new_file_name = str_replace(' ', '-', $new_file_name);
$new_file_name = substr($new_file_name, 0, -strlen($ext));
$new_file_name .= $extension;
// File Name
$move_file = move_uploaded_file($file['tmp_name'], $upload_image_to_folder.$new_file_name);
if($move_file)
{
$done = 'The image has been uploaded.';
}
}
else
{
@unlink($file['tmp_name']);
}
$file_uploaded = true;
}
?>
Please check the code now. I just need to change the line
if(!empty($_FILES))
such that if someone select any file then if condition will be true but if they don’t select any file i.e if they keep the field blank then if condition will be false
You could also check like: