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”]
<?php
// bgallz.org – 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(in_array($ext,$valid_exts)){
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”]);
}
if($image){
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.
imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);

// Create image file with 100% quality.
if(is_dir($directory)){
if(is_writable($directory)){
imagejpeg($tmp,$directory.$filename,100) or die(‘Could not make image file’);
if(file_exists($directory.$filename)){
// 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
rename($directory.$filename,$directory.$strip_ext.”.ico”);
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.’;
}

imagedestroy($image);
imagedestroy($tmp);
} 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).”;
}
}
?>
[/codesyntax]

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” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>PHP Favicon Generator Script from bgallz.org</title>
</head>

<body>
<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>
</select>
<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!” />
</form>
<p><a href=”https://bgallz.dev/488/php-favicon-generator-script/” target=”_blank”>PHP Favicon Generator Script</a> from <strong>bgallz.org</strong></p>
[/codesyntax]

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”]
<?php
if(isset($_GET[“do”])){
if($_GET[“do”] == “create”){
if(isset($_POST[“submit”])){

// 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.”;

}
}
}
?>
[/codesyntax]

 

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

[code lang=”html4strict”]
</body>
</html>
[/code]

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
</FilesMatch>
[/code]

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: , , , , , , ,

23 Comments

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

    Thanks

  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 http://favicon.zz.mu 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.

    <?php
    include"db.php";
    function favicon($file=""){
    $date=date('d-M-y-h-m-s');
    global $path;
    $path="favicons/razzbee".$date.".ico";
    $size=getimagesize($file);
    list($width,$height)=$size;
    $new_width="16";
    $new_height="16";
    $favicon=imagecreatetruecolor($new_width,$new_height);
    if(eregi("(.gif)$",$file)){
    $image=imagecreatefromgif($file);
    }
    elseif
    (eregi("(.png)$",$file)){
    $image=imagecreatefrompng($file);
    }
    else{
    $image=imagecreatefromjpeg($file);
    }$GLOBALS[last];
    imagecopyresampled($favicon,$image,0,0,0,0,$new_width,$new_height,$width,$height);
    if(eregi("(.gif)$",$file)){
    $last=imagegif($favicon,$path);
    }
    elseif
    (eregi("(.png)$",$file)){
    $last=imagepng($favicon,$path);
    }
    else{
    $last=imagejpeg($favicon,$path);
    return $last;
    }
    }
    if(success){
    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:


      $favicon=imagecreatetruecolor($new_width,$new_height);
      $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 *
Website