Generate a Dynamic favicon with PHP




If you don't have a favicon.ico file prepared, you can use this simple script to dynamically generate a PNG file with custom background color and a single letter in the center. This is convenient as a temporary favicon.

The favicon.php script

Here is the example favicon.png that will do a few things:

  1. Create a blank image of size 32x32
  2. Change the background color to an RGB value
  3. Overlay text on to the image
  4. Set the response type to be PNG
  5. Return the image data
 * `favicon.php` - Dynamically generate a favicon image with background color and text overlay
 * PHP Image Processing and Generation

// Generate a plain black image first
$generated_image = imagecreate(32, 32);
// Set background color using RGB values
imagecolorallocate($generated_image, 0, 255, 0);  // #00FF00 Green

// Add text overlay to image. This adds a single character: `!`
// To use other fonts, call `imageloadfont()`
$text_color = imagecolorallocate($generated_image, 0, 0, 255); // #0000FF Blue
imagestring($generated_image, 5, 12, 8,  '!', $text_color);

// Return the actual image as a proper PNG response
header('Content-Type: image/png');
imagepng($generated_image); // Write binary data to output stream
imagedestroy($generated_image); // Ensure memory is freed

HTML template

In the HTML code, you would specify the favicon in the <head> section like this:


    <link rel="icon" href="/favicon.php" sizes="32x32" type="image/png">




After reading this you should be able to create a dynamically generated favicon for your web application.