Skip to content

Instantly share code, notes, and snippets.

@svandragt
Last active January 23, 2024 10:52
Show Gist options
  • Save svandragt/9bd3353c278c04fa5d4c36449c50056e to your computer and use it in GitHub Desktop.
Save svandragt/9bd3353c278c04fa5d4c36449c50056e to your computer and use it in GitHub Desktop.
Dynamic icon based on HTTP_HOST
<?php
/**
* `favicon.php` - Dynamically generate a favicon image with background color and text overlay
*/
$fallback = 'favicon.ico';
if ( file_exists( $fallback ) ) {
// use a favicon.ico if available
header( "Location: $fallback" );
die( "Redirecting to $fallback" );
}
if ( ! function_exists( 'imagecreate' ) ) {
// requires GD functions
die( "GD not installed." );
}
$http_host = filter_var( $_SERVER['HTTP_HOST'] ?? '', FILTER_SANITIZE_URL );
$hash = md5( $http_host );
$text = substr( $http_host, 0, 1 );
$generated_image = imagecreate( 32, 32 );
if ( ! $generated_image ) {
die( 'Could not create image.' );
}
// Extract three pairs of hexadecimal values from the hash
$red = hexdec( substr( $hash, 0, 2 ) );
$green = hexdec( substr( $hash, 2, 2 ) );
$blue = hexdec( substr( $hash, 4, 2 ) );
imagecolorallocate( $generated_image, $red, $green, $blue );
// Add text overlay to image. This adds the first character of the hostname
$text_color = imagecolorallocate( $generated_image, 0, 0, 255 );
imagestring( $generated_image, 5, 12, 8, $text, $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
@svandragt
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment