Check if file is ANY image (general check)- PHP - php

I could of course check mime types through the exif_imagetype or getimagesize and check mime types one by one... But I just want ANY image - I dont care what type... So I was wondering - can I do something like this: ?
// PHP manual says: Determine the type of an image
// and that Imagetype Constants are 1-17 so :
$tmp_imagetype = exif_imagetype('image.gif');
if ( ($tmp_imagetype>=1) && ($tmp_imagetype<=17) ) {
echo "It is an image!";
} else{
echo "It isn't an image.";
}
Can I rely on that?
What happens when the file is not an image? Will it just return non-image constant value or will it throw a warning or error
Thanks

You really don't need all that you just need the following as exif_imagetype returns false if its not an image
if($imagetype = exif_imagetype('image.gif')){
// its an image
} else {
// its not an image
}

You could check if the function returns (exactly) FALSE:
$file="SOMEFILE";
if(exif_imagetype($file)===FALSE){
print("NOT IMAGE");
}else{
print("IMAGE");
}

Why don't you just put all types of images in an array and then check it with this code:
if(in_array($value, $array)) {
//it's an image! Hooray!
}else {
//it's not.
}

Related

How to determine whether passed into the function path or image?

For example I have function named test in which I do some stuff with image. I want to be able detect if in it was passed the image or only the path to it. For example:
function test($image) {
// here I need to detec if $image is path or loaded image
}
test('/home/name/image.jpg');
test(file_get_contents('/home/name/image.jpg'));
Assuming you have these sanitized:
if (file_exists($image)) {
// path
} else {
// image
}
Probably you’ll want to check whether an image is the proper image using some image handling library in the else clause.
Use getimagesize($image);. If it has a width and height, it's an image.See http://php.net/manual/en/function.getimagesize.php for full info.
$image_size = getimagesize($image);
$image_size[0] > 0 ? /*It's an image*/ : /*It's not*/;
Try this
function test($image) {
if($image=='')
{
return false;
}
if(file_exists($image))
{
echo "file exists";
}
else
{
echo "path is passed to the function";
}
}
test('/home/name/image.jpg');
test(file_get_contents('/home/name/image.jpg'));
you can use is_file for this
Tells whether the given file is a regular file.

How can I check that at-least one file is selected for upload

how can I check that user has selected at-least one file for upload in below code ?
i have tried with in_array, isset, !empty functions but no success
please note that userfile input is array in html
if(!empty($_FILES['userfile']['tmp_name'])){
$upload_dir = strtolower(trim($_POST['name']));
// Create directory if it does not exist
if(!is_dir("../photoes/". $upload_dir ."/")) {
mkdir("../photoes/". $upload_dir ."/");
}
$dirname = "../photoes/".$upload_dir;
for($i=0; $i < count($_FILES['userfile']['tmp_name']);$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i]))
{
$messages[] = 'No file selected for no. '.$i.'field';
}
/*** check if the file is less then the max php.ini size ***/
if($_FILES['userfile']['size'][$i] > $upload_max)
{
$messages[] = "File size exceeds $upload_max php.ini limit";
}
// check the file is less than the maximum file size
elseif($_FILES['userfile']['size'][$i] > $max_file_size)
{
$messages[] = "File size exceeds $max_file_size limit";
}
else
{
// copy the file to the specified dir
if(#copy($_FILES['userfile']['tmp_name'][$i],$dirname.'/'.$_FILES['userfile']['name'][$i]))
{
/*** give praise and thanks to the php gods ***/
$messages[] = $_FILES['userfile']['name'][$i].' uploaded';
}
}
}
}else{
$messages[] = 'No file selected for upload, Please select atleast one file for upload';
dispform();
}
Here's how I do it its a couple of if's and I use a for loop as I allow multiple file uploads from a single drop down but its the if's that are more important to you
$uploaded = count($_FILES['userfile']['name']);
for ($i=0;$i<$uploaded;$i++) {
if (strlen($_FILES['userfile']['name'][$i])>1) {
// file exists so do something
} else {
//file doesn't exist so do nothing
}
}
You'll note I compare against the name element of the global $_FILES this is because you should never be able to upload a file without a name which also applies for no file uploaded
Don't do it client side thats a dumb place to do validation as the user can simply turn js processing off in the browser or it can be blocked by certain addons etc or intercepted and altered via firebug and various browser search hijacking toolbars etc.
Anything like this should always be done server side!
finally I found the answer, I am giving it here for other users,
I have 5 keys in html input array so array index is up to 4
if(!empty($_FILES['userfile']['tmp_name'][0]) or !empty($_FILES['userfile']['tmp_name'][1]) or !empty($_FILES['userfile']['tmp_name'][2]) or !empty($_FILES['userfile']['tmp_name'][3]) or !empty($_FILES['userfile']['tmp_name'][4])){
//at-least one file is selected so proceed to upload
}else{
//no file selected, notify user
}
There are several methods of doing this with PHP (e.g. Check if specific input file is empty), but with JS it's faster and less expensive on the server. Using jQuery you can do this:
$.fn.checkFileInput = function() {
return ($(this).val()) ? true : false;
}
if ($('input[type="file"]').checkFileInput()) {
alert('yay');
}
else {
alert('gtfo!');
}

php script for upload image not working

i have a edit page that allow users to upload a profile image using forms
but the problem is that i keep getting the the format is not acceptable even if the image type is one of the accepted format.
this is the code
if(isset($_POST['parse_var']) == "pic")
{
if(!$_FILES['fileField']['tmp_name'])
{
$errorMSG = '<font color= "#FF0000">Please browse for an Image Before you press the button.</font>';
}
else
{
$maxfilesize = 51200;//in bytes = 50kb
if($_FILES['fileField']['size']>$maxfilesize)
{
$errorMSG = '<font color="#FF0000">Your image was too large, please try again.</font>';
unlink($_FILES['fileField']['tmp_name']);
}
elseif(!preg_match("^.(gif|jpg|png)$/i^",$_FILES['fileField']['name']))
{
$errorMSG = '<font color="#FF0000">Your Image was not one of the accepted format, please try again</font>';
unlink($_FILES['fileField']['tmp_name']);
}
else
{
$newname = "image01.jpg";
$place_file = move_uploaded_file($_FILES['fileField']['tmp_name'],"members/$id/".$newname);
$message='<font color="#00FF00>Your Image has been upload successfully</font>';
}
}//end else
}//end if
Major problems:
a)
elseif(!preg_match("^.(gif|jpg|png)$/i^",$_FILES['fileField']['name']))
^---
you should not be using a regex metachar as the pattern delimiter. Try
preg_match('/\.(gif|jpg|png)$/i', ...) instead.
But in a bigger picture view, you shouldn't be matching on filenames at all. Filenames can be forged. You should be doing server-side MIME-type determination (e.g. via file_info()) instead.
b)
you are NOT properly checking for upload success. The presence of a ['tmp_name'] in the $_FILES array means NOTHING. failed uploads can STILL produce a tmp_name, yet you end up with garbage. Always use something like this:
if ($_FILES['fileField']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['fileField']['error']);
}
the error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php
c) (minor)
you do no need to unlink the temp files. PHP does that automatically when the script exits.
d) (stylistically HUGE error)
font tags? in 2013? The 1990s called and want their HTML 1.0 back...

How to test if a user has SELECTED a file to upload?

on a page, i have :
if (!empty($_FILES['logo']['name'])) {
$dossier = 'upload/';
$fichier = basename($_FILES['logo']['name']);
$taille_maxi = 100000;
$taille = filesize($_FILES['logo']['tmp_name']);
$extensions = array('.png', '.jpg', '.jpeg');
$extension = strrchr($_FILES['logo']['name'], '.');
if(!in_array($extension, $extensions)) {
$erreur = 'ERROR you must upload the right type';
}
if($taille>$taille_maxi) {
$erreur = 'too heavy';
}
if(!empty($erreur)) {
// ...
}
}
The problem is, if the users wants to edit information WITHOUT uploading a LOGO, it raises an error : 'error you must upload the right type'
So, if a user didn't put anything in the inputbox in order to upload it, i don't want to enter in these conditions test.
i tested :
if (!empty($_FILES['logo']['name']) and if (isset($_FILES['logo']['name'])
but both doesn't seems to work.
Any ideas?
edit : maybe i wasn't so clear, i don't want to test if he uploaded a logo, i want to test IF he selected a file to upload, because right now, if he doesn't select a file to upload, php raises an error telling he must upload with the right format.
thanks.
You can check this with:
if (empty($_FILES['logo']['name'])) {
// No file was selected for upload, your (re)action goes here
}
Or you can use a javascript construction that only enables the upload/submit button whenever the upload field has a value other then an empty string ("") to avoid submission of the form with no upload at all.
There is a section in php documentation about file handling. You will find that you can check various errors and one of them is
UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
<...>
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.
In your case you need code like
if ($_FILES['logo']['error'] == UPLOAD_ERR_OK) { ... }
or
if ($_FILES['logo']['error'] != UPLOAD_ERR_NO_FILE) { ... }
You should consider checking (and probably providing appropriate response for a user) for other various errors as well.
You should use is_uploaded_file($_FILES['logo']['tmp_name']) to make sure that the file was indeed uploaded through a POST.
I would test if (file_exists($_FILES['logo']['tmp_name'])) and see if it works.
Or, more approperately (thanks Baloo): if (is_uploaded_file($_FILES['logo']['tmp_name']))
We Could Use
For Single file:
if ($_FILES['logo']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
For Multiple files:
if ($_FILES['logo']['tmp_name'][0] == "") {
// No files were selected for upload, your (re)action goes here
}
if($_FILES["uploadfile"]["name"]=="") {}
this can be used
No file was selected for upload, your (re)action goes here in if body
echo "no file selected";
if ($_FILES['logo']['error'] === 0)
is the only right way

Check if the image is a JPEG

I need to check whether a given image is a JPEG.
if ($_FILES["fname"]["error"] > 0) {
$imgData = "hyperlink/holder.jpg";
} else {
$imgData ="hyperlink/" . $_FILES["fname"]["name"];
}
// Only accept jpg images
// pjpeg is for Internet Explorer should be jpeg
if (!($_FILES["fname"]["type"] == "image/pjpeg") ) {
print "I only accept jpg files!";
exit(0);
}
When it goes to first statement in the first if statement it always gives I only accept jpg files!
How can I fix it?
Try the exif_imagetype image function.
Example:
if(exif_imagetype($filepath) != IMAGETYPE_JPEG){
echo 'Not a JPEG image';
}
PHP has such good image-type support, i wonder why you are restricting your app. In just a couple lines of code you can deal with any input format and convert to jpeg, if that is a requirement...
$im = imagecreatefrompng(input_filename)
imagejpeg($im, output_filename);
I believe the following works:
Also note that:
(exif_imagetype($ImagePathAndName) == IMAGETYPE_JPEG)
only reads the first few bytes looking for an image header so isn't really good enough to confirm if an image is corrupt.
Below I have it in a logical “and” statement i.e. both of these tests must be passed in order for the image to qualify as being valid and non-corrupt etc:
if ((exif_imagetype($ImagePathAndName) == IMAGETYPE_JPEG) && (imagecreatefromjpeg( $ImagePathAndName ) !== false ))
{
echo 'The picture is a valid jpg<br>';
}
Note: You need to place this line of code at the top of the php code in order to avoid seeing the warning messages from imagecreatefromjpeg( $ImagePathAndName ) when it encounters a fake/corrupt image file.
ini_set(‘gd.jpeg_ignore_warning’, 1);
Why don't you try creating an array of exceptions (the files you want the user to be able to upload).
// Hyperlink for your website
$hyperlink = "http://www.yourwebsitehere.com";
if($_FILES['fname']['error'] > 0)
{
$image= $hyperlink . "/holder.jpg";
}
else
{
$image = $hyperlink . "/" . $_FILES['fname']['name'];
}
// Only accept files of jpeg format
$exceptions = array("image/jpg", "image/jpeg", "image/pjpeg");
foreach($exceptions as $value)
{
if($_FILES['fname']['type'] != $value)
{
echo "I only accept jpeg images!";
break; // Or exit();
}
}
When using $_FILES, you are relying on informations sent by the client, which is not the best thing to do (you've seen it's not always the same, and, if I remember correctly, $_FILES['...']['type'] can be faked).
If you are using PHP >= 5.3 (or can install PECL packages), maybe you can give a look to the extension Fileinfo. If you are using an older version, what about mime_content_type?
And, as said by Scott, why allow only jpeg?
Looking about the code better : when you are in the first case (error > 0), you are assigning a default file to $imgData? Why the spaces around "hyperlink"?
And why do you always use to check the content-type, even if there was an error a couple of lines before?
To finish, did you have a look at the manual (Handling file uploads)?
Check the mime (Multipurpose Internet Mail Extensions) type of file with this code. And verify your desired type. You can also detect png,gif with this code.
if($_FILES["fname"]["type"] == "image/jpeg")
{
echo "File type is JPEG";
}

Categories