Tag: PHP

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

PHP Ordinalize Numbers – Add Suffix

Here is a very simple function to use to ordinalize numbers in PHP. This adds the place value suffix to numbers. So you can turn numbers like 1, 2, 3 into 1st, 2nd, 3rd.

Here is the code:

[code lang=”php”]
function ordinalize($int){
if(in_array(($int % 100),range(11,13))){
return $int . “th”;
} else {
switch(($int % 10)){
case 1:
return $int . “st”;
break;
case 2:
return $int . “nd”;
break;
case 3:
return $int . “rd”;
break;
default:
return $int . “th”;
break;
}
}
}
[/code]

Basically the function first checks if the number is in the range of 11-13, and if so it returns the number with “th” attached (11th, 12th, 13th). If it is not in this range it checks the remainder of the number divided by 10.

So let’s say our number was 34. 10 goes into 34 three times, with a remainder of 4. Now the function runs this value against three cases, those being 1, 2, and 3. Since it is not one of them, the default value is used, which is “th.” Thus returning “4th.”

Example input:

[code]
3
10
999
[/code]

Example output:

[code]
3rd
10th
999th
[/code]

Enjoy!

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , ,

PHP error_reporting() Function

The error_reporting() function determines what errors are reported from the current script.

Here is the syntax for this function:

Syntax

[code lang=”php”]
error_reporting(report_level);
[/code]

The report_level parameter is optional and specifies what report level to report for the current script. This can be set by its numeric value or its constant name, however for future versions of PHP it is recommended you use the constant name rather than the numeric value.

Report Levels

Value Constant Description
1 E_ERROR Fatal run-time errors. Errors that can not be recovered
from. Execution of the script is halted
2 E_WARNING Non-fatal run-time errors. Execution of the script is not
halted
4 E_PARSE Compile-time parse errors. Parse errors should only be
generated by the parser
8 E_NOTICE Run-time notices. The script found something that might be
an error, but could also happen when running a script normally
16 E_CORE_ERROR Fatal errors at PHP startup. This is like an E_ERROR in the
PHP core
32 E_CORE_WARNING Non-fatal errors at PHP startup. This is like an E_WARNING
in the PHP core
64 E_COMPILE_ERROR Fatal compile-time errors. This is like an E_ERROR
generated by the Zend Scripting Engine
128 E_COMPILE_WARNING Non-fatal compile-time errors. This is like an E_WARNING
generated by the Zend Scripting Engine
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by
the programmer using the PHP function trigger_error()
512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING
set by the programmer using the PHP function trigger_error()
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the
programmer using the PHP function trigger_error()
2048 E_STRICT Run-time notices. PHP suggest changes to your code to help
interoperability and compatibility of the code
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be
caught by a user defined handle (see also set_error_handler())
8191 E_ALL All errors and warnings, except level E_STRICT (E_STRICT
will be part of E_ALL as of PHP 6.0)

Here is an example of the error_reporting function in PHP:

[code lang=”php”]

[/code]

Filed under: PHP, Web ProgrammingTagged with: , ,

PHP Global Variables with Functions

Here we’re going to take a look at variables inside and outside of PHP functions. It is very easy to make one error with a function and have it return the wrong value. We’re going to make a simple function named “func1” which we’ll tweak a bit to show how variables are used inside and out of functions in PHP.

Here is our function, take a look and see if you can tell what the output of the function will be:

[code lang=”php”]

[/code]

The output is nothing right now. haha So if you thought it was anything but nothing, that’s wrong. The function has no code in it whatsoever right now, and the variable “$var” is set to equal the returned value of the function “func1().” Since the function does nothing, $var is equal to nothing. Easy enough. Now let’s work with some variables.

[code lang=”php”]

[/code]

Now, we have a parameter to our PHP function. A parameter is any variable that is defined within the function’s parentheses. You can have many parameters in your functions – seperated by commas – but it is  a good idea to keep your functions organized and simple to their purpose. So we have $var as a parameter to func1(). You can use these to submit values through a function and work with them inside the function to return a different or desired value. Right now, the function func1() is just returning $var. So whatever is put through as $var initially, will be returned back as it was.

So this code will result in the output:

hello

Let’s say we want to have a global variable we can use in several functions. Global variables are defined as such within a function as previously defined variables outside the function. In the following code we’ll define $name as “Brian” and use it in two functions.

[code lang=”php”]
“;
echo $goodbye;

?>
[/code]

The output of this code will be:

Hello Brian!
Goodbye Brian!

You can use global variables with PHP pages you include on other PHP pages. For example if you have variables defined on one PHP page, in this example “variables.php,” you can call that page to another and globally define variables in your functions to work with them and return what you like.

Variables.php:
[code lang=”php”]

[/code]

Now on our page we are working on, we’ll call it “display.php,” we’ll call the page variables.php and use these variables in functions.

Display.php:
[code lang=”php”]

[/code]

The output of this code will be:

Hello Brian! Thanks for visiting bgallz.org.

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , , ,

PHP Search a Mysql Database

Nearly every website has some kind of search feature that allows you to quickly find the specific things you are looking for. This can be done a number of ways depending on the language and desired features, but I am going to show you how to search a Mysql database using PHP and a simple HTML form. The form is going to submit two variables – “q” and “submit.” The “submit” variable will tell PHP to initiate the search, and “q” will be the defined search terms that it searches the database for.

First, we need the HTML form. We do this with the “form” tags and “input” tags as the keywords and search button.

[code lang=”html”]


[/code]

This form is sending the two variables to the page “search.php.” This is where we will search our mysql database for rows that match the terms. First we will clean the search terms using trim() and addslashes() which will remove any whitespace and add backslashes “\” before any quotation marks, etc. so it isn’t a threat to our mysql database.

Visit my post on Mysql Database Connect to see how to connect to the database.

[codesyntax lang=”php” title=”search.php Source Code”]
<?php

// search.php
if(isset($_POST[“submit”])){
// Form was submitted, collect the search terms.
$search = trim(addslashes($_POST[“q”]));
if($search){
// We got the search terms, now lets search the database.
// Connect to database here.
$sql = mysql_query(“SELECT * FROM table1 WHERE column1 LIKE ‘%$search%'”);
$count = mysql_num_rows($sql);
// This will search column1 in table1 for a match of the search terms. The parentheses before and after the terms allow the search terms to be a part of other text.
if($count > 0){
// Matches were found!
echo “<p>Search: \”<em>”.$search.”</em>\” – “.$count.” Results Found.</p>”;
echo “<table width=\”100%\” align=\”center\” border=\”1\” cellpadding=\”3\” cellspacing=\”0\”>”;
echo “<tr><th align=\”left\”><strong>Search Results</strong></th></tr>”;
while($row = mysql_fetch_array($sql)){
echo “<tr><td align=\”left\”>”.$row[“column1″].”</td></tr>”;
}
echo “</table>”;
}
} else {
echo “Please enter search terms.”;
}
} else {
// Form wasn’t submitted, redirect to index.php.
header(“Location: index.php”);
}
[/codesyntax]

You can personalize the mysql query however you like of course. Edit the values “table1” and “column1” to match the table you are searching in your database and the columns you want to match the search terms to. You can even match them against multiple columns like so:

[code lang=”php”]
$sql = mysql_query(“SELECT * FROM table1 WHERE column1 LIKE ‘%$search%’ OR column2 LIKE ‘%$search%'”);
[/code]

This will try to match the search terms to column1 or column2. This will make your search range larger, thus bringing more results to your viewers. Of course when displaying your results in the table above it would be smart to include things like: date/time it was submitted, who it was submitted by, category, etc. You can do this by including other columns when you echo the data into the table, like so:

[code lang=”php”]
while($row = mysql_fetch_array($sql)){
echo “

“.$row[“column1″].” “.$row[“column2″].” “.$row[“column3″].”

“;
}
[/code]

So let’s say you wanted to display posts in a table from users, when it was posted, the last reply, etc. You would have it displayed as so:

Title Last Reply Posted By Time Posted
HTML Linking Stylesheets May 1st, 2010 bgallz April 16th, 2010
Another Post May 1st, 2010 bgallz April 16th, 2010
Another Post May 1st, 2010 bgallz April 16th, 2010
Filed under: MySQL, PHP, TutorialsTagged with: , , ,

PHP Timestamps time()

One of the most common ways to capture the current time in PHP scripting is by using the time() function. This returns the current timestamp which is the number of seconds after a certain date and time in the past. You can use this when entering a mysql query to note the current time of whatever action you are capturing.

We must be connected to a Mysql database in order to submit the value(s) to the database. You can see how to connect to a mysql database here.

For example, lets say we want to capture the current time of when a form is submitted:

[code lang=”php”]
timestamp where the Username field matches a specified value. We will use the date() function to echo the timestamp into a date format. We will use the m/d/Y format:

  • d – Represents the day of the month (01 to 31)
  • m – Represents a month (01 to 12)
  • Y – Represents a year (in four digits)

View a complete list of the PHP date() format list here!

Like so:

[code lang=”php”]
0){
$row = mysql_fetch_assoc($sql);
echo “You joined on: “.date(“m/d/Y”,$row[‘time’]).”.”;
} else {
echo “User has not joined!”;
}
?>
[/code]

This will output the code as such:

You joined on: 05/31/2010.

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , ,

PHP Create Thumbnail Images

Here we are going to observe how to use PHP to generate thumbnails for us. A thumbnail is a smaller size and usually smaller quality of an image shown as preview or link to the original image. Thumbnails can be very useful for faster loading times and quicker display of images on your web pages and a few other reasons. This script will allow us to use a directory on our server and convert all image files in it to a new thumbnail, with dimensions we want, and save it on a new thumbnails directory.

We do this using some PHP functions. First we have to open the directory that we specify as the directory to the images we want to convert to thumbnails. We use the function opendir().

The next part:

[code lang=”php”]
while (false !== ($fname = readdir($dir))) {
[/code]

This loops through the directory until it reaches the end of the files stored in the directory.

Then we make sure it is an image file type by checking its extension:

[code lang=”php”]
$valid_extensions = array(“jpg”,”gif”,”png”,”jpeg”);
if(in_array(strtolower($info[‘extension’]),$valid_extensions)){
[/code]

We use the function imagecreatefromjpeg() to make an image out of the file with the image extension. With this we grab the image’s width and height to calculate the new height of the thumbnail based off of the $thumbWidth specified in the beginning of the function (200).

We then use the function imagecreatetruecolor() to make a temporary image for the new thumbnail. With it we transfer it to a new image file in our thumbnails directory with the following code:

[code lang=”php”]
$genThumb = imagejpeg($tempImage,$pathToThumbs . rand(100,999) . $fname);
[/code]

The rand(100,900) make a random 3 digit number in front of the file name. Remove it if you wish.

Here is our function:

[code lang=”php”]

function generateThumbs(){
$pathToScreens = “../screenshots/”; // Directory to your images you want converted to thumbnails.
$pathToThumbs = “../screenshots/thumbs/”; // Directory to your thumbnails.
$thumbWidth = 200; // Width of the thumbnails generated.

$dir = opendir($pathToScreens) or die(“Could not open directory”);
$counter = 0;

while(($fname = readdir($dir)) !== false){
if($fname != “.” && $fname != “..”){
// Remove folders.
$valid_extensions = array(“jpg”,”jpeg”); // Only jpeg images allowed.
$info = pathinfo($pathToScreens . $fname);
if(in_array(strtolower($info[“extension”]),$valid_extensions)){
// Make sure the file is an image file by checking its extension to the array of image extensions.
$img = imagecreatefromjpeg($pathToScreens . $fname); // Select the file as an image from the directory.
$width = imagesx($img);
$height = imagesy($img);
// Collect its width and height.

$newHeight = floor($height * ($thumbWidth / $width)); // Calculate new height for thumbnail.

$tempImage = imagecreatetruecolor($thumbWidth,$newHeight); // Create a temporary image of the thumbnail.
// Copy and resize old image into new image.
imagecopyresized($tempImage,$img, 0, 0, 0, 0, $thumbWidth,$newHeight,$width,$height);

$genThumb = imagejpeg($tempImage,$pathToThumbs . rand(100,999) . $fname);
// Create the thumbnail with the new width and height in the thumbnails directory.
// I added a rand 3 digit number in front of the file name to avoid overwrite.
$counter++; // Increment.
}
}
}
if($counter > 0){
return $counter . ” thumbnails generated from the directory \””.$pathToScreens.”\”.”;
} else {
return “No image files could be processed.”;
}
closedir($dir); // Close the directory.
}

?>
[/code]

Then we can just call it like so:

[code lang=”php”]
echo generateThumbs();
[/code]

Filed under: Scripts, TutorialsTagged with: , ,

PHP Switch Function

The function switch() in PHP is used to execute different codes based on a variable’s value. This is used in place of the IF/ELSE IF statements. A default value is optional and, if specified, is used when no other option is matched. You must include a break; after each case or the following cases will all return true.

[code lang=”php”]

[/code]

You can use this with forms and such to determine an action based on a submitted value as well! Here is an example using the switch() function in a form:

[code lang=”html”]

Select your gender:

[/code]

Now on our PHP side of the script (submit.php) we will use the switch() function to evaluate the value.

[code lang=”php”]

[/code]

Filed under: PHP, Web ProgrammingTagged with: , ,

PHP Users Online with Mysql

Using PHP and Mysql you can keep track of the users online your website and display it on your page.

First thing ,we need a table in our Mysql database for the users online. So let’s make a table in our database.

[code lang=”sql”]
mysql_query(“CREATE TABLE online(
id INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
ip_address VARCHAR(25) NOT NULL,
timestamp VARCHAR(25) NOT NULL)”) or die(mysql_error());
[/code]

Now that we have the table, we need to update the users online on every page. That way it is most accurate and up to date with who is currently online. We will set a time offset so that we include all users online within the past 5 minutes.

[code lang=”php”]
0){
mysql_query(“UPDATE online SET timestamp = ‘”.time().”‘ WHERE ip_address = ‘$ip’) or die(mysql_error());
} else {
mysql_query(“INSERT INTO online (ip_address,timestamp) VALUES (‘$ip’,'”.time().”‘)”) or die(mysql_error());
}
$delete = mysql_query(“DELETE FROM online WHERE timestamp < '$time_offset'") or die(mysql_error()); ?>
[/code]

Now every time someone goes on a page with this code, mysql will check to see if the user is in the system, and if so update their current timestamp, otherwise create a row for them in the table. It will also erase any rows with old timestamps. This will keep the table clean and updated.

Now we count the users online and show it on the page.

[code lang=”php”]
‘$time_offset'”);
$online = mysql_num_rows($sql);

return ‘There are ‘.$online.’ user(s) currently online. ‘;
}
?>
[/code]

Filed under: TutorialsTagged with: , ,

PHP Display Mysql Rows with Column Limit

This little script is very useful for having a set width of a table and displaying several rows organized in that table.

It is easy to just display a table full of rows for all the data in a mysql table. Something like this:

[code lang=”php”]
0){
echo “

“;
echo “

“;
while($row = mysql_fetch_array($sql)){
echo “

“;
}
echo “

“.$row[“col1″].”

“;
}
?>
[/code]

This will grab all content of the mysql table and put the data from column 1 as a table column in this table.

Let’s say we have some images we want to display. The table is 500 pixels wide. So if your images are no larger than 100 pixels, you would want to display 5 columns per row in your table. This will give it good organization and flow in your webpage.

[code lang=”php”]
0){
echo “

“;
echo “

“;
for($i=0;$i<=mysql_num_rows($sql);$i=$i+1){ while($row = mysql_fetch_array($sql)){ $i++; if($i%5==0){ // use the operator to find the remainder of $i / 5 (%) // if the remainder is 0; it is a multiple of 5, so make a new row. echo " “;
} else {
echo “

“;
}

}
}
echo “

“;
}
?>
[/code]

The two codes will appear like so:

Before Column Limit:

Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7 Image 8 Image 9 Image 10

After Column Limit:

Image 1 Image 2 Image 3 Image 4 Image 5
Image 6 Image 7 Image 8 Image 9 Image 10
Filed under: TutorialsTagged with: , , ,