PHP Favicon Generator Script

I decided to make a free easy to use favicon generating script that uses PHP. The script has a few features and requirements when uploading your image to be converted to a favicon. First the script checks for a few things such as file type, file size, if the directory is writable, and the specified dimensions. You can create a 16×16 icon or a 32×32 icon.

This PHP Favicon Generator Script first checks the form submitted for the following:

  • Valid file size. (Default: Max 75kb)
  • Valid file types. (Valid extensions are defaulted to image files)
  • Writable directory for favicons.

Then, once verifying these variables, we create a temporary image file on our server with the new dimensions gathered from the form (16×16 or 32×32). We then copy the uploaded image file’s contents over to the temporary file, while resizing it. Once the temporary image file has the new width, height, and copied graphical output, we can transfer this temporary data to a file on our server. Finally, we rename this image file to have a favicon file extension (.ico). Wallah!

Click here to check out the demo for this script!

Just select the image file you want converted to a 16×16 or 32×32 icon and hit submit! It’s that easy.

Here’s the PHP function we want to include in our header, prior to loading the HTML:

[codesyntax lang=”php” title=”Favicon Generator Script”]
// – Web coding and design tutorials, scripts, resources and more.
// favicon Generator Script
function generate_favicon(){
// Create favicon.
$postvars = array(“image” => trim($_FILES[“image”][“name”]),
“image_tmp”        => $_FILES[“image”][“tmp_name”],
“image_size”    => (int)$_FILES[“image”][“size”],
“image_dimensions”    => (int)$_POST[“image_dimensions”]);
$valid_exts = array(“jpg”,”jpeg”,”gif”,”png”);
$ext = end(explode(“.”,strtolower(trim($_FILES[“image”][“name”]))));
$directory = “./favicon/”; // Directory to save favicons. Include trailing slash.
$rand = rand(1000,9999);
$filename = $rand.$postvars[“image”];

// Check not larger than 175kb.
if($postvars[“image_size”] <= 179200){
// Check is valid extension.
if($ext == “jpg” || $ext == “jpeg”){
$image = imagecreatefromjpeg($postvars[“image_tmp”]);
else if($ext == “gif”){
$image = imagecreatefromgif($postvars[“image_tmp”]);
else if($ext == “png”){
$image = imagecreatefrompng($postvars[“image_tmp”]);
list($width,$height) = getimagesize($postvars[“image_tmp”]);
$newwidth = $postvars[“image_dimensions”];
$newheight = $postvars[“image_dimensions”];
$tmp = imagecreatetruecolor($newwidth,$newheight);

// Copy the image to one with the new width and height.

// Create image file with 100% quality.
imagejpeg($tmp,$directory.$filename,100) or die(‘Could not make image file’);
// Image created, now rename it to its
$ext_pos = strpos($rand.$postvars[“image”],”.” . $ext);
$strip_ext = substr($rand.$postvars[“image”],0,$ext_pos);
// Rename image to .ico file
return ‘<strong>Icon Preview:</strong><br/>
<img src=”‘.$directory.$strip_ext.’.ico” border=”0″ title=”Favicon  Image Preview” style=”padding: 4px 0px 4px 0px;background-color:#e0e0e0″ /><br/>
Favicon successfully generated. <a href=”‘.$directory.$strip_ext.’.ico” target=”_blank” name=”Download favicon.ico now!”>Click here to download your favicon.</a>’;
} else {
“File was not created.”;
} else {
return ‘The directory: “‘.$directory.'” is not writable.’;
} else {
return ‘The directory: “‘.$directory.'” is not valid.’;

} else {
return “Could not create image file.”;
} else {
return “File size too large. Max allowed file size is 175kb.”;
} else {
return “Invalid file type. You must upload an image file. (jpg, jpeg, gif, png).”;

Then we must include the HTML form that will submit the image and dimensions to PHP:

[codesyntax lang=”html4strict” title=”HTML Form”]
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “”>
<html xmlns=””>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>PHP Favicon Generator Script from</title>

<h2>Create Your Favicon</h2>
<form action=”index.php?do=create”  enctype=”multipart/form-data” method=”post”>Image Dimensions:<br />
<select style=”width: 170px;” name=”image_dimensions”>
<option selected=”selected” value=”16″>16px x 16px</option>
<option value=”32″>32px x 32px</option>
<p><span style=”font-size: 14pt;”>Favicon Image:</span></p>
<input name=”image” size=”40″ type=”file” />
<input style=”font: 14pt verdana;” name=”submit” type=”submit” value=”Submit!” />
<p><a href=”” target=”_blank”>PHP Favicon Generator Script</a> from <strong></strong></p>

So we have the function included in our header, and the form is presented by the code above. Now we just need to call the function when our GET value for “do” is set to “create” – which the form does for us.

Here is the PHP to include after the HTML form:

[codesyntax lang=”php” title=”After Form PHP”]
if($_GET[“do”] == “create”){

// Call the generate favicon function and echo its returned value
$gen_favicon = generate_favicon();
echo $gen_favicon;
echo “Place your download instructions and anything else you want here to follow the download link after upload.”;



Also be sure to follow this PHP with the closing tags for HTML:

[code lang=”html4strict”]

Be sure to include the HTML head tags in your HTML pages that use the favicon. These are given on the script’s index and on the demo.

This header HTML looks like this:

<link rel="shortcut icon" type="image/x-icon" href="./favicon.ico">


How to Force Download for .ico Files

Open a new text document in notepad. Paste the following code within the document:

[code lang=”htaccess”]
<FilesMatch “\.(?i:ico|gif|png|jpg|jpeg)$”>
Header set Content-Disposition attachment

Now save this file as “.htaccess” exactly like that. Place this file in the directory you are saving your .ico files to for download. This will force the access of these files (ico, png, gif, jpeg) to be a download only type.

Thanks for reading!

Click here to download the script!

Filed under: PHP, Scripts, TutorialsTagged with: , , , , , , ,


  1. Will be using it on my website improvement site 🙂


  2. Its amazing, loing at the time and effort you put into your blog and detailed information you provide. I’ll bomark your blog and visit it weekly for your new posts o

  3. I’ve been struggling to sort out a favicon for my client on his site theme. But inow i’m using Favicon generator and it’s great!.It helps me a lot.

  4. wow, awesome post, I was wondering how to cure acne naturally. and found your blog by bing, many userful stuff here, now i have got some idea. bookmarked and also signed up your rss. keep us updated.

  5. Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!

  6. Thank you for a genuinely useful script, it’s hard to find a favicon PHP script on the web!

  7. png image, the Black background

    Hopes to repair … Thank YOu!!

  8. nice script. i will use it in my own site to genarate ico. thanks for your work

  9. Excellent script. It will be a nice addition to our free seo tools service.

  10. Need help, how to change background color black to white..

    • If you background color is already set to black there is most likely a stylesheet you are loading.

      You want to look for:

      body {
      background-color: #000;

      and change the #000 to #fff.

      Or, you might have the background color set on the body tag like so:

      Not sure what you are working with here.

  11. @Brian:
    I mean, when uploading icon, I want the background of the icon is white. Please visit my website and upload an icon, and see the icon background is black. So I want to change to white.

    • Oh I see. I am at work right now so I can’t test this out just yet, but try the following:

      $tmp = imagecreatetruecolor($newwidth,$newheight);
      $color = imagecolorallocate($tmp, 255, 255, 255); // white background

      The php function imagecreatetruecolor automatically creates a black background image, to change the background color use the imagecolorallocate function.

      Let me know how this works.

  12. Sorry late reply, busy with other things. This is my php script using the name “creator.php”. You can make me where to fill your script tell. I am a beginner, do not know much about php.

    function favicon($file=""){
    global $path;
    return $last;
    include "show_favicon.php";

    • I’m not sure what you want me to include to this script. If you are referring to the white background add-on that I posted in reply to your last comment, you would want to include the following:

      $color = imagecolorallocate($favicon, 255, 255, 255); // white background

      Try that and get back to me.

  13. I try not work, still black background color

  14. Thank you Brian, I’m sorry too late. File that has been sent in your inbox

Add a Comment

Your email address will not be published. Required fields are marked *

Comment *
Name *
Email *