gray
gray

Reputation: 1018

PHP - Get file extension (image) without knowing it

How can I get the extension of an image file without knowing what it is? I have tried using glob, as below, but it returns an error: "Array Notice: Undefined offset: 0"

$path=BASEURL."content/images/profile_images/".$imageName;
$results= glob($path.'.*');

$filename = $results[0];
echo $filename;

Upvotes: 0

Views: 2186

Answers (5)

KevBot
KevBot

Reputation: 18908

You can "explode" the end of the filename to get the extension.

$file = 'image.jpg';
$temp = explode(".", $file);
$extension = end($temp);
echo $extension;

Will output "jpg"

Upvotes: 0

noahnu
noahnu

Reputation: 3574

According to the code you posted as an answer, this will work:

$dir = "content/images/profile_images/";
$results = glob("{$dir}{$imageName}.*");

if(count($results)>0){
   echo pathinfo($results[0], PATHINFO_EXTENSION);
}

It appears that your error was an invalid file path. The image was not at that path which contained the BASEURL.

Upvotes: 1

gray
gray

Reputation: 1018

This works for me, but it is not the best way:

$path="content/images/profile_images/".$image; 

$file = $path.".";

$ext = array("jpg", "jpeg", "JPEG", "gif", "png", "bmp");
for($x = 0; $x < 6; $x++)
{
    $image = $file.$ext[$x];
    if(file_exists($image))
    {
        $pic=$image;
        echo $pic;
    }
}

Upvotes: 0

woofmeow
woofmeow

Reputation: 2408

Use PHPs built in function pathinfo like this

$ext = pathinfo($filename, PATHINFO_EXTENSION);

For example

echo pathinfo("http://www.google.com//swf/fvere.ext",PATHINFO_EXTENSION);
//Output : ext

Read the manual here.

Hope that helps :)

Upvotes: 1

Sammitch
Sammitch

Reputation: 32272

Your glob is bad and it's returning an empty array, hence the error. It's not a regular expression, it's a shell expansion and * is a wildcard. Currently it will try to match any filename that begins with a .. ie. .htaccess.

If you want it to match any file use: glob($path.'*')

If you want it to match any file with a period in it: glob($path.'*.*')

Upvotes: 1

Related Questions