We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

Verifying if an image exists - case insensitive

Denisvt
Denisvt asked
on
Medium Priority
1,269 Views
Last Modified: 2008-02-01
I have a page on my PHP site in which I have to check whether a thumbnail image exists for a particular listing.
Right now it checks if "myimage123.jpg" exists, but I need to extend that search to myimage123.JPG as some digital cameras seem to uppercase the image extension, and those images will be uploaded by the site users. I'd also like to extend the image check to the same name but with alt. extensions, in particular PNG :
I'm not sure how to code in PHP that it should look for myimage123.jpg OR myimage123.JPG OR myimage123.png OR myimage123.PNG, based on the following :


// Pix definition
$housepicBIG1JPG = MY_UPLOAD_DIR.$reference."_1.jpg";
$housepicJPG = MY_UPLOAD_DIR.$reference."_1_mini.jpg";

//Thumb exists ?
if(file_exists($housepicJPG)) {
                              $thumbpiccode="<img src=\"".$housepicJPG."\" alt=\"".$titre."\" class=\"estateselect\" />";
                              $thumbJPG="(Found it)";
                     }
                     // else I create the thumbnail or send a warning etc...


Thanks.

Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2006

Commented:
Hi,

I think you can use the glob() function, although you should test it:

$results = glob('myfilename.*');
if(is_array($results)) {
  print_r($results);
} else {
  //file not found
}

-r-
Brian BushSolutions Architect

Commented:
You have to do it explicitly, but it isn't bad.

$_housepic = substr($housepicJPG, 0 ,strrpos($housepicJPG, "."));

if (file_exists($_housepic . ".jpg") || file_exists($_housepic . ".JPG") || file_exists($_housepic . ".png") || file_exists($_housepic . ".PNG") {
    $thumbJPG = "(Found it)";
} else {
    //etc....

Other than that, you would have to read a dir listing or use a system/exec command or you could
get the File_Find PEAR class to help you search for a pattern:
http://pear.php.net/manual/en/package.filesystem.file-find.php

I think it basically does the directory listing and a regex.
--brian
Brian BushSolutions Architect

Commented:
Actually, Roonaan's right, glob should work.

$_housepic = substr($housepicJPG, 0 ,strrpos($housepicJPG, "."));
$_image = glob($_housepic . ".*");

if ($_image) {
    // already exists.
} else {
    // make a new one.
}

--brian
CERTIFIED EXPERT

Commented:
Hm.. there's not built-in argument for filie_exists to do this, but you can just check two different filenames, one with your original lowercase extension and one with an uppercase version of the extension:

$housepicJPG = MY_UPLOAD_DIR.$reference."_1_mini.jpg";
$ext = substr(strrchr($housepicJPG, "."), 1);
$housepicJPG2 = str_replace($ext, strtoupper($ext), $housepicJPG);

if(file_exists($housepicJPG) || file_exists($housepicJPG2)) {
    $thumbpiccode="<img src=\"".$housepicJPG."\" alt=\"".$titre."\" class=\"estateselect\" />";
    $thumbJPG="(Found it)";
}

Hope that helps!
CERTIFIED EXPERT

Commented:
If your server is case sensitive when it comes to displaying images, then change the if statements in my code to the following:

if(file_exists($housepicJPG)) {
    $thumbpiccode="<img src=\"".$housepicJPG."\" alt=\"".$titre."\" class=\"estateselect\" />";
    $thumbJPG="(Found it)";
} elseif (file_exists($housepicJPG2)) {
    $thumbpiccode="<img src=\"".$housepicJPG2."\" alt=\"".$titre."\" class=\"estateselect\" />";
    $thumbJPG="(Found it)";
}

Also, a note on glob... There's a comment on PHP.net that claims it is case sensitive with Windows.  Don't know how it behaves in Unix.
Georgiana GligorCTO / Owner

Commented:
I would suggest having an array of possible extensions, something like:
$aExtensions = array( 'jpg', 'JPG', 'gif', 'GiF' );

When you need to make a new check, you should just add the missing extension to this array. The following code should check everything else:
function checkFileExistence( $sFilename ){
  $aExtensions = array( 'jpg', 'JPG', 'gif', 'GiF' );
  $bReturn = false;
  foreach( $aExtensions as $sExt ){
    if( file_exists( $sFilename . '.' . $sExt ) ){ $bReturn = true; break; }
  }
  return( $bReturn );
}

Cheers,
  GB
As you said, users can upload photos.

A simple solution is to lowercase the chars in the upload process. Then you do not need to bother with uppercase or lowercase letters after that.
Your code will become much more simple! =)


Best regards,

Commented:
There is one very simple solution:

$housepicJPG ='/somePath/someImaGeName.JPG';
if(file_exists( strtolower($housepicJPG ) )) {
...
}


strtolower() first maked all charecters low so, image.jpg = ImAGe.JPG  and so on.
in the same way you can use trtoupper(), but strtolower() is more commonly used for that.
CERTIFIED EXPERT

Commented:
Syrma, that would not work, as his actual file is what would have the uppercase extension.  If you use strtolower in that way, and the actual extension is in uppercase, it will fail.

Commented:
it will work in windows, and not in linux, but I don't what is his system.
still it can be used anyway.
strtolower() might be used during the thumb creation, so all filenames are lowercase, or it can be used here:

rename( $housepicJPG, strtolower($housepicJPG ));
if (file_exists(strtolower( $housepicJPG))){

}

Commented:
Or like this:

$result=false;
if ($handle = opendir('/path/to/files')) {

   while (false !== ($file = readdir($handle))) {
       if (strtolower($file)==strtolower($housepicJPG)){
            $result=true;
         }
   }

   closedir($handle);
   echo $result;
}

Author

Commented:
Many interesting replies, quickly too !
Thanks to all those who contributed. A few elements :
By using
$_image = glob($_housepic . ".*");
wouldn't I allow any extension to be uploaded and then inserted, hence creating a security breach ? I usually am very conservative with those points and I'd rather like to define exactly which extensions are allowed. I like my security best when I base it on "anything that's not explicitely allowed is forbidden" ;-)

I also wish I could take care of the extension case during the upload process, but for various reasons I work on the part where that's already happened beyond my control. My question was also to know, as we allow users to upload pNG or JPGs as they choose, how I could detect if an image of such and such extensions were here, so this was not about case only.
I'll try the suggested solutions, I must say having that checking as a function where extensions can be easily added, as gicutza_cj suggested, looks like the easiest in my case.

Thanks.


Author

Commented:
One note, especially gicutza_cj : I guess $sFilename would be submitted to the function as "myhouse1" ?
More than just a true or false result to know if the pic does exist, I need to know its extension because if it does exist it will be displayed hence the full name must be known, or reconstructed with the initial name and found extension.
CTO / Owner
Commented:
If you need to know the exact extension from the function, it's easy enough to change the return value of it:

/**
 * @param string $sFilename Name of the file, no extension provided at this point
 * @return string Case-matched extension of the file, if it exists; null otherwise
 */
function checkFileExistence( $sFilename ){
  $aExtensions = array( 'jpg', 'JPG', 'gif', 'GiF' );
  $sReturn = null;
  foreach( $aExtensions as $sExt ){
    if( file_exists( $sFilename . '.' . $sExt ) ){ $sReturn = $sExt; break; }
  }
  return( $sReturn );
}

Usage:
if( ! is_null( $sExt = checkFileExistence( $sFilename ) ) ){
  // do your job here
}

Cheers,
  GB

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
Thanks for the comments and examples, I did find a solution to my issue, regards.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.