Ryan
Ryan

Reputation: 69

Get image type, PHP

I'm trying to figure out how to set an image type as a variable in PHP. I need to pull an image from the database, find it's image type and display it. At the moment it's only displaying jpg's.

The code for uploading is:

if(isset($_FILES['image']) && $_FILES['image']['tmp_name'] != '') {
    $tempext = explode('.', $_FILES['image']['name']);
    $tempext = strtolower($tempext[count($tempext) - 1]);
    switch($tempext) {
        case 'jpg':
        case 'jpeg':
            $ext = '.jpg';
            break;
        case 'gif':
            $ext = '.gif';
            break;
        case 'png':
            $ext = '.png';
            break;
        default:
            $ext = false;
    }
    if($ext != false && move_uploaded_file($_FILES['image']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/img/profiles/' . $id . $ext)) {
        $imagesuccess = chmod($_SERVER['DOCUMENT_ROOT'] . '/img/profiles/' . $id . $ext, 0644) ? 'yes' : 'no';
    } else {
        $imagesuccess = 'no';
    }
}

EDIT:

I've made a bit of progress, mostly cleaning up some foolish mistakes, but I still haven't gotten any images to appear.

Here's the updated switch case:

switch ($ext) { 
            case 'jpg':
            case 'jpeg':
                $ext = '.jpg';
                break;
            case 'gif':
                $ext = '.gif';
                break;
            case 'png':
                $ext = '.png';
        }

and image placement:

if(!file_exists($_SERVER['DOCUMENT_ROOT'] . $imgurl . 'profiles/' . $r['id'] . $ext)) {
                    echo '<img src="' . $imgurl . 'profiles/unavailable.gif" id="profile-big-img" />' . PHP_EOL;
                } else {
                    echo '<p><img class="profileimg" src="' . $imgurl . 'profiles/' . $r['id'] . $ext . 'id="profile-big-img" alt="' . $r['forename'] . ' ' . $r['surname'] . (($r['course'] == 'graphics') ? ' Graphic Design' : ' Illustration') . '" /></p>' . PHP_EOL;
                }

Upvotes: 0

Views: 1113

Answers (3)

George
George

Reputation: 1

you can check with the pathinfo function. I'm pretty sure it should work.

Upvotes: 0

sakhunzai
sakhunzai

Reputation: 14500

Its hard to trace the issue when code is bit CREAMY ;)

Lets check what is the issue with your images first from command line :

a) open Terminal b) cd to dirctory with images ( probably web a directory) c) Run this on ( copy +past + Enter)

 php -r  ' $dh= opendir(".");while(($file=readdir($dh))!==false){ if(!is_dir($file)){ $tp=exif_imagetype($file);echo "$file:  =====> $tp\n"; } } '

The output will be sth like this :

...
error.JPG:  =====> 2
features.JPG:  =====> 2
kunfu_panda.jpg:  =====> 2
.....

compare the codes with Imagetype Constants provided by php .

That will be first Step towards the solution.

Upvotes: 1

tereško
tereško

Reputation: 58454

The most reliable way would be to use FileInfo.

Upvotes: 4

Related Questions