phpfilenames

Change tab name using php when displaying a file/image


I'm currently creating a php page that receives an image from one API and shows that image (this php allows the user to define the image dimensions using GET methods).

I want that this php file displays the name of the image (or something I want to put there) on the tab. Is it possible just using php?

This is my current code:

$filename = "...";

// Content type
header('Content-Type: image/jpg');

//I tried this but this is just for download
// header('Content-Disposition: Attachment;filename=image.png');

...

// Get new sizes
list($width, $height) = getimagesize($filename);

$newwidth =  150;
$newheight = 150;
        
...

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefrompng($filename);


// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        
// Output
imagepng($thumb);

Solution

  • PHP does not have direct control of the browser. In fact, the browser doesn't know that PHP even exists.

    The way HTTP works, from the browser's point of view is this:

    1. You enter a URL in your browser's address bar, or click a link, e.g. https://example.com/foo/bar?a=1#bar
    2. The browser looks at the first part of the URL, between https:// and the next / and connects to whatever server it sees there (e.g. example.com)
    3. Then it looks at the rest of the URL (or everything up to the # sign, if there is one), and sends a request to the server, e.g. GET /foo/bar/?a=1
    4. The server replies with some headers, and the body data. The body data is basically a file you're transmitting; it doesn't have any HTTP-specific bits, those are all in the headers.
    5. The browser then has to interpret that and decide what to display. The most important header is Content-Type, which tells the browser if the body data is an HTML page, a JPEG image, a PDF, etc.

    From PHP's point of view, everything happens between steps 3 and 4:

    1. The server receives a request, e.g. GET /foo/bar/?a=1
    2. Some PHP code runs, and outputs some headers and some data
    3. The end.

    Hopefully this explains why there can't be any PHP-specific way to change the title of a browser tab. There are only two things that could influence it:

    To my knowledge, there is no HTTP header for specifying a browser tab title. If you're outputting an HTML page, you can use the <title> tag in the response body. But a JPEG or PNG file doesn't have a "title", so there is nowhere you can output that.

    You could however generate an HTML page, and within that page have an <img> tag pointing to the actual image.