Category: Tutorials

PHP Upload and Resize Image

Many times when you upload a image somewhere you want to resize it to different dimensions based off of a maximum width or height. Here is a simple script that does this for you, using a HTML form and a PHP script. We start with the PHP script that will run if our $_GET[‘do’] is set to “upload.” Then we include the HTML form that has three inputs (max width, max height, image file).

Use the Upload and Resize Demo Here!

Download This Script!

Here is the PHP for our function – generate_resized_image() – which will take the given image file, create a new file on our server, and then copy the uploaded image to our local image file with the new width and height:

[codesyntax lang=”php” title=”Upload and Resize PHP Code”]
<?php

// index.php

function generate_resized_image(){

$max_dimension = 800; // Max new width or height, can not exceed this value.
$dir = “./images/”; // Directory to save resized image. (Include a trailing slash – /)

// Collect the post variables.
$postvars = array(
“image”    => trim($_FILES[“image”][“name”]),
“image_tmp”    => $_FILES[“image”][“tmp_name”],
“image_size”    => (int)$_FILES[“image”][“size”],
“image_max_width”    => (int)$_POST[“image_max_width”],
“image_max_height”   => (int)$_POST[“image_max_height”]
);

// Array of valid extensions.
$valid_exts = array(“jpg”,”jpeg”,”gif”,”png”);

// Select the extension from the file.
$ext = end(explode(“.”,strtolower(trim($_FILES[“image”][“name”]))));

// 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”]);
}
// Grab the width and height of the image.
list($width,$height) = getimagesize($postvars[“image_tmp”]);

// If the max width input is greater than max height we base the new image off of that, otherwise we
// use the max height input.
// We get the other dimension by multiplying the quotient of the new width or height divided by
// the old width or height.

if($postvars[“image_max_width”] > $postvars[“image_max_height”]){

if($postvars[“image_max_width”] > $max_dimension){
$newwidth = $max_dimension;
} else {
$newwidth = $postvars[“image_max_width”];
}
$newheight = ($newwidth / $width) * $height;

} else {

if($postvars[“image_max_height”] > $max_dimension){
$newheight = $max_dimension;
} else {
$newheight = $postvars[“image_max_height”];
}
$newwidth = ($newheight / $height) * $width;
}

// Create temporary image file.
$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 random 4 digit number for filename.
$rand = rand(1000,9999);
$filename = $dir.$rand.$postvars[“image”];
// Create image file with 100% quality.
imagejpeg($tmp,$filename,100);
return “<strong>Image Preview:</strong><br/>
<img src=\””.$filename.”\” border=\”0\” title=\”Resized  Image Preview\” style=\”padding: 4px 0px 4px 0px;background-color:#e0e0e0\” /><br/>
Resized image successfully generated. <a href=\””.$filename.”\” target=\”_blank\” name=\”Download your resized image now!\”>Click here to download your image.</a>”;

imagedestroy($image);
imagedestroy($tmp);
} 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]

This function you can define in your header PHP files along with other functions or where ever you would like, so long as it is defined before the call of the function itself.

Here is the HTML for our form to submit the image file and the new dimensions:

[codesyntax lang=”html4strict” title=”HTML Form”]
<form action=”./index.php?do=upload” method=”post” enctype=”multipart/form-data”>
<table width=”100%” align=”center” border=”0″ cellpadding=”2″ cellspacing=”0″>
<tr>
<td align=”left” width=”100″>
New Width:</td>
<td align=”left”><input name=”image_max_width” style=”width: 120px” type=”text” maxlength=”4″ /> px.</td>
</tr>
<tr><td colspan=”2″><strong>OR</strong></td></tr>
<tr>
<td align=”left”>
New Height:</td>
<td align=”left”><input type=”text” name=”image_max_height” style=”width: 120px” maxlength=”4″ /> px.</td>
</tr>
<tr>
<td align=”left”>
Image:</td>

<td align=”left”><input type=”file” name=”image” size=”40″ /></td></tr>
<tr>
<td align=”left” colspan=”2″>
<ol style=”margin:0;padding:3px 0px 3px 15px”>
<li>Max file size: 175 KB.</li>
<li>Allowed extensions: jpg, jpeg, gif, png.</li>
<li>Max Dimension: <em>800</em>px.</li>
</ol>
</tr>
<tr>
<td align=”left” colspan=”2″>
<input type=”submit” name=”submit” value=”Submit!” style=”font: 10pt verdana” />
</td>
</tr>
</table>
</form>
[/codesyntax]

This will create a form that looks like this:

Max Width: px.
Max Height: px.
Image:
  1. Max file size: 175 KB
  2. Allowed extensions: jpg, jpeg, gif, png.
  3. Max Dimension: 800px.

 

Okay, so now we have our PHP function defined, included and our HTML contains this form submitting the image file and its new dimensions. All we need now is a short code of PHP to check our GET values, particularly do for the value upload. This tells us the form was submitted and we can start checking it for values, and creating our re-sized image.

Here is the PHP which will appear below the HTML form to show our re-sized image once the form is submitted:

<?php

if(isset($_GET['do']) && $_GET['do'] == "upload")
{

$upload_and_resize = generate_resized_image();
echo '<div id="upload">'. $upload_and_resize. '</div>';

}

?>

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

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

Mysql Rows in HTML Option Tag

Let’s say you want to have a simple HTML <select> form as a drop down for rows in a Mysql table. This could be for things like categories, pages, games, anything you want to have in a drop down to navigate to another page or submit a form. What ever the case is, I’m going to make a simple layout for displaying rows returned from a mysql query as <option>’s in a HTML <select> or drop down.

Before we can grab anything from a mysql database we have to connect to it. Find how to connect to a mysql database here.

Let’s make our mysql query first:

[code lang=”php”]

[/code]

This will grab all the rows in “table1” ordered by the value of “id” descending. You can make this query whatever you want whether you want it ordered differently or with other requirements, etc. Now we will just make a <select> inside of a HTML form that holds each of these values as a option.

[code lang=”html”]


Categories

Category:



[/code]

If you have rows returned in you mysql query you will have a HTML drop down that looks like this:

Categories:

This HTML form is being submitted to “index.php?do=nav.” Of course you can point this where ever you want to do whatever you want with it, but let’s say we want to have it direct you to a category with PHP. So we are going to run a function on index.php?do=nav that will redirect the viewer to the category.

[code lang=”php”]

[/code]

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

CSS Drop-Down Menu

Drop down menus are very useful for navigation on websites and for holding many links to pages on your site without taking up much space on your web pages. Using just CSS and Javascript we can make a nice simple drop down menu you can put on your web page. To do this we’ll have three files: dropdown.css, dropdown.js, and index.html. Our index.html page will display the drop down menu and our stylesheet – dropdown.css – will hold the styles for the drop down menu.

Here is a preview of what our drop down menu will look like:

Dropdown.css

[codesyntax lang=”css” title=”Dropdown Stylesheet”]
@charset “utf-8”;
#dropdown {
margin: 0px;
padding: 0px;
list-style-type: none;
text-align: left;
font: 11px Arial, Helvetica, sans-serif;
}
#dropdown li {
float: left;
margin: 0px;
padding: 5px;
list-style-type: none;
border-bottom: 2px solid #cccccc;
border-right: 1px solid #eeeeee;
}
#dropdown li a {
display: block;
margin: 0;
text-decoration: none;
}

#dropdown div {
position: absolute;
visibility: hidden;
margin: 7px 0px 0px 0px;
padding: 0;
background-color: #e8e8e8;
border-right: 1px solid #c5c5c5;
border-bottom: 1px solid #c5c5c5;
}
#dropdown div a {
position: relative;
display: block;
margin: 0;
padding: 3px 6px;
width: auto;
white-space: nowrap;
text-align: left;
text-decoration: none;
font: 11px Verdana, Arial, Helvetica, sans-serif;
color: #333;
border-top: 1px solid #f1f1f1;
border-bottom: 1px solid #e2e2e2;
}
#dropdown div a:hover {
background-color: #f1f1f1;
color: #000;
}
[/codesyntax]

Dropdown.js

[codesyntax lang=”html4strict” title=”Javascript Source Code”]
// Dropdown menu javascript
var timeout    = 500;
var closetimer    = 0;
var ddmenuitem    = 0;

// open hidden layer
function mopen(id)
{
// cancel close timer
mcancelclosetime();

// close old layer
if(ddmenuitem) ddmenuitem.style.visibility = ‘hidden’;

// get new layer and show it
ddmenuitem = document.getElementById(id);
ddmenuitem.style.visibility = ‘visible’;

}
// close showed layer
function mclose()
{
if(ddmenuitem) ddmenuitem.style.visibility = ‘hidden’;
}

// go close timer
function mclosetime()
{
closetimer = window.setTimeout(mclose, timeout);
}

// cancel close timer
function mcancelclosetime()
{
if(closetimer)
{
window.clearTimeout(closetimer);
closetimer = null;
}
}

// close layer when click-out
document.onclick = mclose;
[/codesyntax]

Index.html

[codesyntax lang=”html4strict” title=”Index HTML”]
<!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>Untitled Document</title>
<link href=”./dropdown.css” rel=”stylesheet” type=”text/css” />
<script type=”text/javascript” src=”./dropdown.js”></script>
</head>

<body>
<ul id=”dropdown”>
<li><a href=”#”>Homepage</a></li>
<li><a href=”#” onmouseover=”mopen(‘list1’)” onmouseout=”mclosetime()”>Drop Down Menu #1</a>
<div id=”list1″ onmouseover=”mcancelclosetime()” onmouseout=”mclosetime()”>
<a href=”#”>Drop Down Link #1</a>
<a href=”#”>Drop Down Link #2</a>
<a href=”#”>Drop Down Link #3</a>
</div>
</li>
<li><a href=”#” onmouseover=”mopen(‘list2’)” onmouseout=”mclosetime()”>Drop Down Menu #2</a>
<div id=”list2″ onmouseover=”mcancelclosetime()” onmouseout=”mclosetime()”>
<a href=”#”>Drop Down Link #1</a>
<a href=”#”>Drop Down Link #2</a>
<a href=”#”>Drop Down Link #3</a>
</div>
</li>
<li><a href=”#”>Link #1</a></li>
<li><a href=”#”>Link #2</a></li>
<li><a href=”#” onmouseover=”mopen(‘list3’)” onmouseout=”mclosetime()”>Drop Down Menu #3</a>
<div id=”list3″ onmouseover=”mcancelclosetime()” onmouseout=”mclosetime()”>
<a href=”#”>Drop Down Link #1</a>
<a href=”#”>Drop Down Link #2</a>
<a href=”#”>Drop Down Link #3</a>
</div>
</li>
</ul>
</body>
</html>
[/codesyntax]

Click here to view the live demo!

Click here to download this drop down menu script!

Filed under: CSS, Scripts, TutorialsTagged 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: , , ,

Making a CSS Linkbar with Photoshop

In this post I am going to show you how to make a cool link bar for your website with Photoshop. Link bars are very important in websites as they provide a clear and easy way for viewers to reach other pages on your site. Basically we’ll make a background image which will be set to repeat along the x axis as the background of the cells in our table. Then the links in the link bar will be placed on top of the background image blending in nicely as the buttons on your link bar.

In CSS we make a few styles for the table that will serve as the link bar holder:

style.css

[code lang=”css”]
.link-bar {
padding:0;
border: 2px solid #d8d8d8;
font: 11px tahoma;
}
.link-bar td {
background: #eee url(./images/bg.gif) repeat-x top left;
padding:0;
height: 32px;
}
[/code]

On our server we have to be sure to be placing the images all in the “images” folder in the “public_html” folder – your website’s default directory.

I made a new document with the dimensions 110×32 pixels as the size of a button. You can make them as big as you want for different words or a standard size, whatever you prefer.

1. Make a new layer and fill the layer with the color #EEEEEE as the background color of the link bar.

2. Make another layer and select a lower smaller half portion of the button to shade in with #E5E5E5.

3. Then make your text layer by typing whatever you want onto the canvas with the text tool on the tool panel. I started with “Home” as the first button. You want to apply the following settings to the text layer’s blending options. You can do this by double clicking on the text layer in the layers panel.

Double click the “Home” text layer and apply the settings below or something similar. You can change these grayscale colors to whatever you would like to fit your website’s color theme.

Our first button turns out something as so:

Now, you can make a rollover image if you would like. This will just make the image change when the viewer puts their cursor over it. We’ll add a slight glow on a new layer to make a rollover layer.

Optional Rollover Image Changes

4. Make a new layer. Select the brush tool in the tools panel. Select the 5th brush type, a glowy brush. Set the size to something like 32px and turn the opacity to 50%. Select the color white (#FFFFFF). Here are the settings:

5. At the top of the image drag half of the brush over the very top of the image and the other half off the canvas to make a slight white glow at the top of the image. Here is the result magnified:

Now as the background all we have to do is make a new document with dimensions 1×32. This will be a single line that will repeat as the background. Now do the same you did to the background of the buttons. Make a layer filled in as #EEEEEE and then another layer with 11 pixels or however much you selected along the bottom as #E5E5E5. Here is the background image close up:

Now as the seperator to the images we need to make a seperator image. This will be a very thin image that will sit between the buttons to give them some distinction.

6. Make a new document 2×32 pixels. On one layer copy the background image we made before and stretch it to be 2 pixels wide. (Press Ctrl+T to transform the layer). Make a new layer and fill the middle left half of the image with the color #DADADA and the middle right half with #F6F6F6. Here is the fill-in’s up close:

Now we have our links and our background image. You will need to make a rollover image for every button you want to have one. Now we just have to apply the CSS styles above to our table that will have the link bar images in it. We do this by setting the link tag in the <head> HTML tags.

Insert the following code in the <head> tags:

[code lang=”html”] [/code]

Here is our HTML:

[code lang=”html”]

[/code]

This will produce something like so:

Filed under: CSS, Graphics, TutorialsTagged 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: , ,