Code Examples
These code examples provide a small demonstration of some of the code I've produced for various clients in the past. Examples include PHP, Javascript, CSS and HtAccess files.
Creating a dynamic rss news feed from a MySQL Database
This script receives data from a MySQL database and converts it into xml for the user to subscribe to. The data is added to the database from the CMS which is in turn managed by the owner of the website. Susbcribers of the RSS feed will receive updates automatically every time the CMS is updated with new information.
This is not a complete script but shows most of the important code. Errors may have been introduced by Google Script Highlighter.
$query = "SELECT *
FROM webref_rss_details d
where d.cat_id=$cat_id";
$result = mysqli_query($mysqli, $query);
if(mysqli_num_rows($result)==0)
{
?>
</channel></rss>
<?php
mysqli_free_result($result);
exit;
}
while($row = mysqli_fetch_array($result))
{
echo ''. $row['d_title'] .'
'. $row['d_link'] .'
'. $row['d_description'] .'
'. $row['d_language'] .'
'. $row['d_image_title'] .'
'. $row['d_image_url'] .'
'. $row['d_image_link'] .'
'. $row['d_image_width'] .'
'. $row['d_image_height'] .'
';
}
mysqli_free_result($result);
//Get back items
$query = "SELECT *
FROM webref_rss_items i, webref_rss_details d
WHERE i.detail_id=d.detail_id
AND d.cat_id=$cat_id";
$result = mysqli_query($mysqli, $query);
//Print all items for given news feed.
while($row = mysqli_fetch_array($result))
{
echo '-
'. $row["title"] .'
'. $row["link"] .'
';
}
mysqli_free_result($result);
unset($row);
echo '</channel></rss> ';
Search Engine Friendly Urls using HtAccess
This script alters the url so that it points to a script on the server invisibly.
RewriteEngine on
#RSS news feeds
RewriteRule ^get-rss/([^/\.]+)/?$ /getRSS.php?cat_id=$1
#Rewrite with lots of parameters
RewriteRule ^finance/insurance/([^/\.]+)/([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ /finance_menu.php??id=$1&cat_id=$2&catName=$3&pageTitle=$4
#Media
RewriteRule ^media/([^/\.]+)/?$ /media.php?page=$1
#Categories
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ /newcat.php?category=$1&title=$2
#Latest news
RewriteRule ^news/?$ /news.php?page=news
#Other pages
RewriteRule ^accesskeys/?$ /accesskeys.php
#Search uses POST method to prevent having params in url such as search/keywords/1/
RewriteRule ^search/?$ /search.php
Creating a Price Comparison Website with Shopping.com's XML API
This code is used to connect to the remote XML API which is run by shopping.com. The XML which is produced contains product offers, images and links and can be used to produce an entire price comparison website. The code is a good example of XML and PHP. This particular example returns all category information from the API and outputs a name and id for each.
$bcrumb = 'Home > Shopping';
include_once('../cms/includes/configuration.php');//Include the api config file.
include_once('includes/apiConfiguration.php');//Include the api config file.
include_once('includes/apiFuncs.php');//Include the api config file.
echo $file= API_DOMAIN.'/publisher/3.0/rest/CategoryTree?apiKey='.API_KEY.'&trackingId='.TRACKING_ID.'&categoryId=0&showAllDescendants=true';//construct the api url
$response = new SimpleXMLElement($file,null,true);//run query
$errors=scom_errors($response);
//Print errors.
if(!$errors)
{
echo "
";
foreach($response->category->categories->category as $cat)//process results.
{
echo "
"."".$cat->name.'('.$cat['id'].')';
if(isset($cat->categories))
{
$subcat='';
foreach($cat->categories->category as $cat2)
{
if(!in_array($cat2['id'],$removeCats))
{
$subcat.= "".$cat2->name." (";
$subcat.= "".$cat2['id']."), ";
}
}
echo "
".$subcat;
}
else
{
echo "
No subcategories";
}
}
}
else
{
echo $errors;
}
Resize images in BMP, JPEG, GIF, or Png using PHP
This code is used to resize images in a variety of formats and produces a thumbnail as close as possible to the required size. The code works with all the stated formats including PNG files with Alpha transparency, a known issue when resizing PNG files. This is not a complete example as there are other functions which have to be utilised to do the conversion.
function resize($img, $thumb_width, $newfilename)
{
$max_width=$thumb_width;
//Check if GD extension is loaded
if (!extension_loaded('gd') && !extension_loaded('gd2'))
{
trigger_error("GD is not loaded", E_USER_WARNING);
return false;
}
//Get Image size info
list($width_orig, $height_orig, $image_type) = getimagesize($img);
switch ($image_type)
{
case 1: $im = imagecreatefromgif($img); break;
case 2: $im = imagecreatefromjpeg($img); break;
case 3: $im = imagecreatefrompng($img); break;
case 6: $im = imagecreatefrombmp($img); break;
default: trigger_error('Unsupported filetype!', E_USER_WARNING);return false; break;
}
/*** calculate the aspect ratio ***/
$aspect_ratio = (float) $height_orig / $width_orig;
$thumb_height = round($thumb_width * $aspect_ratio);
//Ensure height is less than required width and height.
while($thumb_height>$max_width)
{
$thumb_width-=10;
$thumb_height = round($thumb_width * $aspect_ratio);
}
if($image_type==6)//BMP requires imagecreate because it is pallet based.
{
$newImg = imagecreate($thumb_width, $thumb_height);
}
else
{
$newImg = imagecreatetruecolor($thumb_width, $thumb_height);
}
/* Check if this image is PNG or GIF (or bitmap), then set if Transparent*/
if(($image_type == 1) OR ($image_type==3) OR ($image_type==6))
{
imagealphablending($newImg, false);
imagesavealpha($newImg,true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $thumb_width, $thumb_height, $transparent);
}
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig);
//Generate the file, and rename it to $newfilename
switch ($image_type)
{
case 1: imagegif($newImg,$newfilename); break;
case 2: imagejpeg($newImg,$newfilename); break;
case 3: imagepng($newImg,$newfilename); break;
case 6: imagejpeg($newImg, $newfilename); break;
default: trigger_error('Failed resize image!', E_USER_WARNING);return false; break;
}
//return $newfilename;
return true;
}
PHP Login Script
This login script utilises encrypted passwords using md5 and a salt. When the password is first aquired it is encrypted into a special code and stored in the database. When the user comes to login their password is encrypted on the server in the same way and compared with the already encrypted password to determine whether a match has been found. The users details are then stored in session variables on the server whilst the user is logged in.
if(!isset($_POST['user']) || !isset($_POST['pass']))
{
header("Location:".PUBLIC_DIR."loginform.php?message=Please enter a username and password.");
}
if(isset($_POST['submit']))
{
//If the username and pasword exist then check them.
if(!empty($_POST['user']) || !empty($_POST['pass']))
{
$user_entered=escape_data($_POST['user']);
$hashpass=md5(SALT.trim($_POST['pass']).SALT);
$query="select *
from ".LOGIN_TABLE."
where passwd = '".$hashpass."'
and uname_tml = '".$user_entered."'
LIMIT 1";
if($result = mysqli_query($mysqli,$query))
{
if(mysqli_num_rows($result)==1)
{
$row=mysqli_fetch_array($result);
if($row['revoked'])
{
header("Location:".PUBLIC_DIR."loginform.php?message=Your access has been revoked, please speak to the person who administers access to this account.");
exit;
}
else
{
$_SESSION['admin_id']=$row['user_id'];
$_SESSION['title']=$row['title'];
$_SESSION['email']=$row['email'];
$_SESSION['uname']=$row['uname_tml'];
$_SESSION['forename']=$row['fname'];
$_SESSION['surname']=$row['lname'];
$_SESSION['priv_add']=$row['priv_add'];
//Forward the user to their desired dir contianed in 'opt_logindir' db field. (Login_dirs in vars.php)
header("Location:".PUBLIC_DIR);
exit();
}
}
else
{
header("Location:".PUBLIC_DIR."loginform.php?message=Your username and password were incorrect. Please try again or use the forgotten password feature.");
exit;
}
}
else
{
header("Location:".PUBLIC_DIR."loginform.php?message=There was a database error, please contact us about this.");
}
}
else
{
header("Location:".PUBLIC_DIR."loginform.php?message=Please enter a username and password.");
}
}
TinyMCE WYSIWYG Javascript Plugin
This example is an example of TinyMCE, which is a Javascript plugin used to produce a WYSIWYG style interface for users. I have used this heavily on CMS sites to provide users with the ability to add images, bold/italic/underlined text and to provide other capabilities in a easy to understand format.
Using this plugin enabled us to provide a high quality product very easily which to the customer looked to have taken a long time to develop. The TinyMCE plugin can be used in conjunction with image upload scripts to allow the user of the website full control over the content with minimal interference from the developer once it is finished. This is done using the external_image_list_url attribute. Visit this link to see a live demo of TinyMCE.
tinyMCE.init({
mode : "textareas",
theme : "advanced",
theme_advanced_buttons1: "bold,italic,underline, strikethrough,formatselect,bullist, numlist,cleanup, sub,sup, charmap,image",
theme_advanced_blockformats : "p,h1,h2,h3,h4,h5,h6,blockquote",
theme_advanced_buttons2: "",
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing: false,
document_base_url : <?php echo "\"".SITE_URL."\""; ?>,
external_image_list_url : "itpscms/general/imageList.php?type=news",
force_p_newlines: false,
force_br_newlines: true,
convert_newlines_to_brs: false,
remove_linebreaks: true,
paste_auto_cleanup_on_paste: true,
});
CSS Examples, advanced styling
Here are some tricks I use in css. The list includes classes, ids, Internet Explorer hacks, descendent selectors, child selectors, pseudo classes, sibling selector, attribute selectors, and tag styles for example.
/*Apply margin, padding and border 0 to all tags, removes inconsistencies caused by ie.*/
*{margin:0;padding:0;border:0;}
/*Class definitions*/
.smTable
{
width:40%;
}
/*Apply width:25% to first child element of td within a .cms_form class.*/
.cms_form td:first-child
{
width:25%;
}
/*Apply margin-top = 10px to input elements with attribute type=file*/
input[type="file"]
{
margin-top:10px;
}
/*Apply width=40% to input elements with attribute type=text and with class of cms_date*/
input[type="text"].cms_date
{
width:40px;
}
/*Apply following values to following input types*/
input[type="text"],input[type="password"],input[type="file"]
{
border:1px solid #999;
width:60%;
padding:2px;
}
/*Apply to all textarea tags*/
textarea
{
width:400px;
height:400px;
}
/*ID definition, only affects one element*/
#content_padding
{
width:99%;
}
/*Apply to body with logout id*/
body#logout
{
background-color:#fff;
}
/*Apply list-style-image to li tags with minus_icon class.*/
li.minus_icon
{
list-style-image:url("../images/minus_icon.gif");
}
/*Styles to set particular link apperance using :link and :hover pseudoclasses.*/
a.imitateButton
{
background-color:#c7c7c7;
color:#666;
}
a.imitateButton:link{color:#666;}
a.imitateButton:hover{color:#666;}
/*Apply following to h1 tags next to a div tag with datePosted class.*/
h1+div.datePosted
{
margin-bottom:10px;
float:left;
clear:both;
}
/*Apply to .menuNav class when inside html>body, not understood by ie6, so an ie hack.*/
html>body .menuNav /*Standard compliant sizes.*/
{
width:111px;
height:19px;
}
/*Ie hack to apply to ie7 only*/
html > body .boxes
{
* padding-top:20px;
}