开发者

redirecting browser to a new image, with content type image/png in PHP

开发者_开发技巧I have a php script which generates an image, and is used (mainly) like this:

<img src="user_image.php?id=[some_guid]" />

The script uses a class I wrote to display an image matching that ID. There are a number of things that could go wrong though, and each of them throws an exception. So I have something like this:

<?php

try {

    if( ! isset($_GET['id']) ) throw new Exception;

    $images = new User_Images;
    $images->display($_GET['id']);

} catch( Exception $e ) {

    header('location: images/link_error.png');

}

If I view this from the browser, everything is fine -- if there was an error the address in the address bar changes to images/link_error.png and displays that instead.

But when this script is used in an <img> tag, and there is an error grabbing the image, it doesn't show up at all.

Do header redirects not work this way? What is another way that I can do this?

update

There is no problem, browser redirects work perfectly this way, the issue was that my browser was caching the empty image that was returned before the redirect was put in. A hard refresh (Ctrl + F5 for Firefox) fixed it and it started working like normal.


Hummm... My guess is that the

header('Location: images/link_error.png');

Because headers were previously sent?

Try placing an ob_start() on the top of your file and see if it solves your problem.


Here is a simple way to debug this:

try {
    if (!isset($_GET['id'])) throw new Exception;

    $images = new User_Images;
    $images->display($_GET['id']);
} catch (Exception $e) {

    if (headers_sent() === false)
    {
        header('Location: images/link_error.png'); // also try using the absolute URL here
    }

    else
    {
        echo file_get_contents('http://www.google.com/intl/en_ALL/images/logo.gif');
    }
}

If the Google logo shows up, you need to trace where you're outputting data or use ob_start() + ob_end_clean().


this tag is really nice!


Couldn't you just give the error image a default ID (i.e. zero) and use $images->display(0)? Then the error image is handled exactly like the successful case.


Interesting - I would expect a call to a <img> tag to work with a redirect. Anyway, it might not. I'd be interested to hear why not. Anyone?

The easiest workaround that comes to mind is passing through the error image using fopen() and fpasshtru().


A lot of places like PhotoBucket just display an error image when there are problems loading the requested one. This is usually a pre-constructed image that just says "Image Error" or whatever. When images are being put together dynamically, there aren't many other options than this other than returning a 404.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜