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:


try {

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

    $images = new User_Images;

} 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?


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;
} catch (Exception $e) {

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

        echo file_get_contents('');

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().

Need Your Help

Adding references in a shared (.shproj) project

c# windows xaml windows-phone win-universal-app

I'm having an issue with adding a dll reference to a shared project. As seen in the picture below I have a Universal solution with a project for windows and a project for windows phone.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.