Php
November 30th 2009 // PHP // Permalink
Read CSS files with PHP
This function will open CSS file read it's styles and separate selectors from property value pairs. The function stores the values in two array sessions (names and styles). The values can be then easily retrieved using loops or if/else statements.
PHP functions used
file - Reads entire file into an array
trim - Strip whitespace (or other characters) from the beginning and end of a string
This function returns a string with whitespace stripped from the beginning and end of str.
strtok - Tokenize string
strtok() splits a string (str) into smaller strings (tokens), with each token being delimited by any character from token. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.
strstr - Find first occurrence of a string
Returns part of haystack string from the first occurrence of needle to the end of haystack.
count - Count elements in an array, or properties in an object
Returns the number of elements in var, which is typically an array, since anything else will have one element.
PHP % operator
I will be using Modulus (%) operator which returns a remainder of $a divided by $b.
Sample CSS
I am going to use this simple CSS file (style_sheet.css) to help me explain the PHP code
p{
color:#000000;
}
h1{
font-size:18px;
color:#666666;
}
table{
width:100%;
border:1px solid #000000;
}
PHP code
I chose to use comments to explain how the PHP code works, so for those of you who actually want to know how the code works, please read the comments. :)
//if no style loaded load
$lines = file("style_sheet.css");
foreach ($lines as $line_num => $line) {
$cssstyles .= trim($line);
}
//using strtok we remove the brackets around the css styles
$tok = strtok($cssstyles, "{}");
//For example, the style: p{color:#000000;} now looks like this p color:#000000;
//crete another array in which we will store tokenized string
$sarray = array();
//set counter
$spos = 0;
//with this while loop we are basically separating selectors from styles and store those values in the $sarray
while ($tok !== false) {
$sarray[$spos] = $tok;
$spos++;
$tok = strtok("{}");
}
//if you run print_r($sarray); the result would be:
//Array ( [0] => p [1] => color:#000000;
// [2] => h1 [3] => font-size:18px;color:#666666;
// [4] => table [5] => width:100%; border:1px solid #000000;)
//As you can see all selectors are stored in odd number positions of the array and styles in even.
//That is an important piece of information that we will use to to go through $sarray and store
//all selectors in one array and styles in the other.
// To start we need to get the size of $sarray
$size = count($sarray);
//create selectors and styles arrays
$selectors = array();
$sstyles = array();
//set counters
$npos = 0;
$sstl = 0;
//a simple for loop with modulus operator will help us separate styles from selectors.
for($i = 0; $i<$size; $i++){
if ($i % 2 == 0) {
$selectors[$npos] = $sarray[$i];
$npos++;
}else{
$sstyles[$sstl] = $sarray[$i];
$sstl++;
}
}
//all that's left is store names and styles in a session for us to use
$_SESSION['style_names'] = $selectors;
$_SESSION['style_styles'] = $sstyles;
//now if you run print_r($selectors); and print_r($sstyles);
//you'll notice that you can access individual selectors and it's styles using array keys
//In this example $selectors[0] value is "p" and $sstyles[0] value is "p" property/value pair-color:#000000;
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
November 28th 2009 // PHP // Permalink
Using MySQL left JOIN and right JOIN
MySQL left or right JOIN can be very helpful and it refers to the order in which the tables are put together and the results are displayed.
Left Join
When using LEFT JOIN all rows from the first table will be returned whether there are matches in the second table or not. For example, if table users contains users main information and table options contains users optional information, any records in options table would be tied to a particular id in the users table.
"SELECT name, lastname, optonalinfo FROM users LEFT JOIN options ON users.id = options.id"
The result of this query would return name and lastname values from the users table and all available values from the options table. NULL is returned for non-existing values in options table.
| name | lastname | optionalinfo |
| Scott | Walls | NULL |
| Jerry | Wern | DOB: 02/03/1979 |
| Gina | Ruff | NULL |
Right Join
RIGHT JOIN works just like the LEFT JOIN but with table order reversed. All rows from the second table are going to be returned whether or not there are matches in the first table. But in case of users and options tables there is only one record in options table. This means that only one of three rows will be displayed.
"SELECT name, lastname, optionalinfo FROM users RIGHT JOIN options ON users.id=options.id"
| name | lastname | optionalinfo |
| Jerry | Wern | DOB: 02/03/1979 |
These are two most common types of JOINS available in MySQL. There are also INNER, CROSS JOIN, STRAIGHT JOIN and NATURAL JOIN. To learn about these visit http://mysql.com
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
No Comments
November 24th 2009 // PHP // Permalink
PHP class to get remote page title and description
This PHP class will help you get remote page title and description. Could be useful for automating link exchanges.
PHP functions that are doing most work are:
class.metatags.php
class metatags {
var $title = '';
var $description = '';
var $error_invalid_url = 'Error'; //message to display if the url can't be loaded
var $error_no_title = 'Untitled'; //display if title is not set
var $error_no_desc = 'None set'; //display if description is not set
function getmetadata($url){
//make sure URL is formated correctly
if (strstr($url, 'http://') == false){
$url = 'http://'.$url;
}
//get file contents
$d = file_get_contents($url);
//display error if site can't be loaded
if (!$d) {
echo $this->error_invalid_url;
exit();
}
//shorten string
$line = substr($d, 0, 3000);
//remove linebreaks from the string
$linebreaks = array("\r\n", "\n", "\r");
//Processes \r\n's first so they aren't converted twice.
$line = str_replace($linebreaks, '', $line);
// This only works if the title and its tags are on one line
if (eregi ("(.*) ", $line, $out)) {
$this->title = $out[1];
}
//get description
$desc = get_meta_tags($url);
$this->description = $desc['description'];
}
//get title
function get_title(){
if(!$this->title){
return $this->error_no_title;
}else{
return $this->title;
}
}
//get description
function get_description(){
if(!$this->description){
return $this->error_no_desc;
}else{
return $this->description;
}
}
}
Usage
include("class.metatags.php");
$meta = new metatags();
$meta->getmetadata("http://www.yahoo.com");
//get title
echo $meta->get_title();
//get description
echo $meta->get_description();
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
December 16th 2009
Jarod B - I think you should of also made it so that they could set the title from outside the class to, via the functions. like this: function get_title($show=""){ if(!$this->title){ return $this->error_no_title; }else{ $title = (!empty($show)) ? " " . $show; : $this->title; return $title; // EX: get_title("More"); = "More" OR get_title() = "TITLE NAME" } } -------- http://www.jarodsworlds.ismywebsite.com/
November 23rd 2009 // PHP // Permalink
PHP visitor tracking script with jQuery and Raphael JavaScript library
This simple PHP visitor tracking script uses jQuery and Raphael javascript library to display daily hits to your page. The class features:
- IP filter (for IP's you don't want to track)
- Unique visits counter
- Raphael analytics (example on the bottom of the page)
- No search engine robots tracking
- Total hits counter
- Visitor IP's info
- Visitor host info
- Referring pages info
- Visited pages info
- MySQL log table creation
Dependencies
MySQL Table
This table could be expanded as needed. For example, you could add "browser" field to collect visitor browser information.
CREATE TABLE IF NOT EXISTS 'logger' (
'log_id' int(11) NOT NULL auto_increment,
'ip' varchar(16) NOT NULL default '',
'host' varchar(100) NOT NULL default '',
'visitdate' datetime NOT NULL default '0000-00-00 00:00:00',
'host' varchar(255) NOT NULL default '',
'ref_domain' varchar(255) NOT NULL default '',
PRIMARY KEY ('logid')
) TYPE=MyISAM
PHP Class (class.logger.php)
IMPORTANT: Make sure to fill in the database info. See comments for the details.
class logger {
//database setup
//MAKE SURE TO FILL IN DATABASE INFO
var $hostname_logon = ''; //Database server LOCATION
var $database_logon = ''; //Database NAME
var $username_logon = ''; //Database USERNAME
var $password_logon = ''; //Database PASSWORD
//table fields
var $tablename = ''; //logger table name
var $filter = array(); //array of ip's you don't want tracked
//connect to database
function dbconnect(){
$connections = mysql_connect($this->hostname_logon, $this->username_logon, $this->password_logon) or die ('Unabale to connect to the database');
mysql_select_db($this->database_logon) or die ("Error in query: $qry. " . mysql_error());
}
//log visit
function logvisit($ip, $host, $filename, $ref_domain){
//check if ip is filtered
if(!in_array($ip,$this->filter)){
$qry = "INSERT INTO ".$this->tablename." (ip, host, visitdate, filename, ref_domain)VALUES('".$ip."','".$host."',NOW(),'".$filename."', '".$ref_domain."' )";
$result = mysql_query($qry) or die ("Error in query: $qry. " . mysql_error());
}
}
//show total uniqe visitors to date(parameter: (int) number of months). For example: 3 will start counting from 3 monhts before today.
function totalunique($month){
$lastmonth = mktime(01, 01, 01, date("m")-$month, date("d"), date("Y"));
$from = date("Y-m-d H:i:s", $lastmonth);
$to = date("Y-m-d H:i:s");
$qry = "SELECT DISTINCT ip, visitdate, host FROM ".$this->tablename." WHERE visitdate BETWEEN '".$from."' AND '".$to."' GROUP BY ip";
$result = mysql_query($qry) or die ("Error in query: $qry. " . mysql_error());
$totalunique = mysql_num_rows($result);
return $totalunique;
}
//show total visits to date(parameter: (int) number of months). For example: 3 will start counting from 3 monhts before today.
function totalhits($month){
$lastmonth = mktime(01, 01, 01, date("m")-$month, date("d"), date("Y"));
$from = date("Y-m-d H:i:s", $lastmonth);
$to = date("Y-m-d H:i:s");
$qry = "SELECT ip, visitdate, host FROM ".$this->tablename." WHERE visitdate BETWEEN '".$from."' AND '".$to."'";
$result = mysql_query($qry) or die ("Error in query: $qry. " . mysql_error());
$totalhitsmonth = mysql_num_rows($result);
return $totalhitsmonth;
}
//show daily visits for a specific month / year and div in which to laod the graph
function dailyhits($month, $year, $div, $tableid){
//current month and year
if($month == ""){
$month = date("m");
}
if($year == ""){
$year = date("Y");
}
//get number of days
$numdaysinmonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
echo '< table cellpadding="0" cellspacing="0" border="0" class="'.$tableid.'" >
< tfoot >
';
for($x=1;$x<=$numdaysinmonth;$x++){
echo ''.$x.'';
}
echo '
< /tfoot >
< tbody >
';
$totalhits = 0;
for($y=1;$y<=$numdaysinmonth;$y++){
if($y < 10){
$b = '0'.$y;
}else{
$b = $y;
}
$current_month = date('Y-m').'-'.$b;
$qry = "SELECT DISTINCT ip FROM ".$this->tablename." WHERE visitdate LIKE '$current_month%' GROUP BY visitdate";
$result = mysql_query($qry) or die ("Error in query: $qry. " . mysql_error());
$numrows = mysql_num_rows($result);
echo '';
echo $numrows;
$totalhits = $totalhits + $numrows;
echo '';
}
echo '
< /tbody >
< /table >
';
}
//display visit details (parameter (int) number of last visits to display
function visitdetails($num){
$qry = "SELECT * FROM ".$this->tablename." WHERE visitdate!='' ORDER BY log_id DESC LIMIT 0, ".$num."";
$result = mysql_query($qry) or die ("Error in query: $qry. " . mysql_error());;
if (mysql_num_rows($result) != 0){
echo '< table cellpadding="0" cellspacing="0" border="0" class="visitdetails" >';
echo '< thead>IPHostReferring PagePage Visited< /thead >';
echo '< tbody>';
while ($row = mysql_fetch_object($result)){
$nowww = ereg_replace('www.','',$row->ref_domain);
$domain = parse_url($nowww);
if(!empty($domain["host"])) {
$host = $domain["host"];
}
echo ''.$row->ip.'
'.$row->host.'
'.$host.'
'.$row->filename.'
';
}
echo '< /tbody >';
echo '< /table >';
}
}
//raphael stuff(depends on including raphael.js library
function loadraphael($tableid, $div, $month_year, $width, $height, $leftgutter, $bottomgutter, $topgutter,$strokecolor, $fontcolor,$fillcolor,$gridcolor){
echo '< script type="text/javascript" >
//raphael.path.methods.js
Raphael.el.isAbsolute = true;
Raphael.el.absolutely = function () {
this.isAbsolute = 1;
return this;
};
Raphael.el.relatively = function () {
this.isAbsolute = 0;
return this;
};
Raphael.el.moveTo = function (x, y) {
this._last = {x: x, y: y};
return this.attr({path: this.attrs.path + ["m", "M"][+this.isAbsolute] + parseFloat(x) + " " + parseFloat(y)});
};
Raphael.el.lineTo = function (x, y) {
this._last = {x: x, y: y};
return this.attr({path: this.attrs.path + ["l", "L"][+this.isAbsolute] + parseFloat(x) + " " + parseFloat(y)});
};
Raphael.el.arcTo = function (rx, ry, large_arc_flag, sweep_flag, x, y, angle) {
this._last = {x: x, y: y};
return this.attr({path: this.attrs.path + ["a", "A"][+this.isAbsolute] + [parseFloat(rx), parseFloat(ry), +angle, large_arc_flag, sweep_flag, parseFloat(x), parseFloat(y)].join(" ")});
};
Raphael.el.curveTo = function () {
var args = Array.prototype.splice.call(arguments, 0, arguments.length),
d = [0, 0, 0, 0, "s", 0, "c"][args.length] || "";
this.isAbsolute && (d = d.toUpperCase());
this._last = {x: args[args.length - 2], y: args[args.length - 1]};
return this.attr({path: this.attrs.path + d + args});
};
Raphael.el.cplineTo = function (x, y, w) {
this.attr({path: this.attrs.path + ["C", this._last.x + w, this._last.y, x - w, y, x, y]});
this._last = {x: x, y: y};
return this;
};
Raphael.el.qcurveTo = function () {
var d = [0, 1, "t", 3, "q"][arguments.length],
args = Array.prototype.splice.call(arguments, 0, arguments.length);
if (this.isAbsolute) {
d = d.toUpperCase();
}
this._last = {x: args[args.length - 2], y: args[args.length - 1]};
return this.attr({path: this.attrs.path + d + args});
};
Raphael.el.addRoundedCorner = function (r, dir) {
var rollback = this.isAbsolute;
rollback && this.relatively();
this._last = {x: r * (!!(dir.indexOf("r") + 1) * 2 - 1), y: r * (!!(dir.indexOf("d") + 1) * 2 - 1)};
this.arcTo(r, r, 0, {"lu": 1, "rd": 1, "ur": 1, "dl": 1}[dir] || 0, this._last.x, this._last.y);
rollback && this.absolutely();
return this;
};
Raphael.el.andClose = function () {
return this.attr({path: this.attrs.path + "z"});
};
//raphael analytics
Raphael.fn.drawGrid = function (x, y, w, h, wv, hv, color) {
color = color || "'.$fillcolor.'";
var path = ["M", x, y, "L", x + w, y, x + w, y + h, x, y + h, x, y],
rowHeight = h / hv,
columnWidth = w / wv;
for (var i = 1; i < hv; i++) {
path = path.concat(["M", x, y + i * rowHeight, "L", x + w, y + i * rowHeight]);
}
for (var i = 1; i < wv; i++) {
path = path.concat(["M", x + i * columnWidth, y, "L", x + i * columnWidth, y + h]);
}
return this.path(path.join(",")).attr({stroke: color});
};
$(function () {
$(".'.$tableid.'").css({
position: "absolute",
left: "-9999em",
top: "-9999em"
});
});
window.onload = function () {
// Grab the data
var labels = [],
data = [];
$(".'.$tableid.' tfoot th").each(function () {
labels.push($(this).html());
});
$(".'.$tableid.' tbody td").each(function () {
data.push($(this).html());
});
// Draw
var width = '.$width.',
height = '.$height.',
leftgutter = '.$leftgutter.',
bottomgutter = '.$bottomgutter.',
topgutter = '.$topgutter.',
colorhue = .6 || Math.random(),
color = "hsb(" + [colorhue, 1, .75] + ")",
r = Raphael("'.$div.'", width, height),
txt = {font: '12px Fontin-Sans, Arial', fill: "'.$fontcolor.'"},
txt1 = {font: '10px Fontin-Sans, Arial', fill: "'.$fontcolor.'"},
txt2 = {font: '12px Fontin-Sans, Arial', fill: "'.$fillcolor.'"},
X = (width - leftgutter) / labels.length,
max = Math.max.apply(Math, data),
Y = (height - bottomgutter - topgutter) / max;
r.drawGrid(leftgutter + X * .5, topgutter, width - leftgutter - X, height - topgutter - bottomgutter, 10, 10, "'.$gridcolor.'");
var path = r.path().attr({stroke: color, "stroke-width": 4, "stroke-linejoin": "round"}),
bgp = r.path().attr({stroke: "none", opacity: .3, fill: color}).moveTo(leftgutter + X * .5, height - bottomgutter),
frame = r.rect(10, 10, 100, 40, 5).attr({fill: "'.$fillcolor.'", stroke: "'.$strokecolor.'", "stroke-width": 2}).hide(),
label = [],
is_label_visible = false,
leave_timer,
blanket = r.set();
label[0] = r.text(60, 10, "24 hits").attr(txt).hide();
label[1] = r.text(60, 40, "22 September 2008").attr(txt1).attr({fill: color}).hide();
for (var i = 0, ii = labels.length; i < ii; i++) {
var y = Math.round(height - bottomgutter - Y * data[i]),
x = Math.round(leftgutter + X * (i + .5)),
t = r.text(x, height - 6, labels[i]).attr(txt).toBack();
bgp[i == 0 ? "lineTo" : "cplineTo"](x, y, 10);
path[i == 0 ? "moveTo" : "cplineTo"](x, y, 10);
var dot = r.circle(x, y, 5).attr({fill: color, stroke: "'.$fillcolor.'"});
blanket.push(r.rect(leftgutter + X * i, 0, X, height - bottomgutter).attr({stroke: "none", fill: "'.$fontcolor.'", opacity: 0}));
var rect = blanket[blanket.length - 1];
(function (x, y, data, lbl, dot) {
var timer, i = 0;
$(rect.node).hover(function () {
clearTimeout(leave_timer);
var newcoord = {x: +x + 7.5, y: y - 19};
if (newcoord.x + 100 > width) {
newcoord.x -= 114;
}
frame.show().animate({x: newcoord.x, y: newcoord.y}, 200 * is_label_visible);
label[0].attr({text: data + " hit" + ((data % 10 == 1) ? "" : "s")}).show().animateWith(frame, {x: +newcoord.x + 50, y: +newcoord.y + 12}, 200 * is_label_visible);
label[1].attr({text: lbl + " '.$month_year.'"}).show().animateWith(frame, {x: +newcoord.x + 50, y: +newcoord.y + 27}, 200 * is_label_visible);
dot.attr("r", 7);
is_label_visible = true;
}, function () {
dot.attr("r", 5);
leave_timer = setTimeout(function () {
frame.hide();
label[0].hide();
label[1].hide();
is_label_visible = false;
// r.safari();
}, 1);
});
})(x, y, data[i], labels[i], dot);
}
bgp.lineTo(x, height - bottomgutter).andClose();
frame.toFront();
label[0].toFront();
label[1].toFront();
blanket.toFront();
};< /script >';
}
//function to create Logger table
function cratetable($tablename){
$qry = "CREATE TABLE IF NOT EXISTS '".$tablename."' (
'log_id' int(11) NOT NULL auto_increment,
'ip' varchar(16) NOT NULL default '',
'host' varchar(100) NOT NULL default '',
'visitdate' datetime NOT NULL default '0000-00-00 00:00:00',
'host' varchar(255) NOT NULL default '',
'ref_domain' varchar(255) NOT NULL default '',
PRIMARY KEY ('logid')
) TYPE=MyISAM";
$result = mysql_query($qry) or die(mysql_error());
return;
}
}
Usage
Make sure to include and instantiate the class on every page you use it.
include("class.logger.php");
$log = new logger(); //Instentiate the class
$log->tablename = "logger"; //set logger table name
$log->dbconnect(); //connect to the database
Create Logger Table
Run this code only once to create the log on table.
include("class.logger.php"); //path to class.logger.php file
$log = new logger(); //Instentiate the class
$log->dbconnect(); //connect to database
//pass the name of the table as the parameter. I.e. 'logger"
$log->cratetable('logger');
Log visits
Create a file logger.php and place it inside a folder "/logger".
include("class.logger.php"); //path to class.logger.php file
$log = new logger(); //Instentiate the class
$log->tablename = "logger"; //set logger table name
$log->dbconnect(); //connect to database
$log->filter = array('00.00.00.000'); //array of IP addresses you don't want to track
//get IP
$ip = $_SERVER['REMOTE_ADDR'];
//get host
$host = gethostbyaddr($_SERVER['REMOTE_ADDR']);
//get fisited page
$filevisited = $_REQUEST['f'];
if($filevisited ==""){
$filevisited = $_SERVER["PHP_SELF"];
}
//get referring page
$ref_domain = urldecode($_REQUEST['r']);
if($ref_domain ==""){
$ref_domain = $_SERVER["HTTP_REFERER"];
}
//log visit
$logger->logvisit($browser, $ip, $host, $filevisited, $ref_domain);
To ensure bot's are not logged add Disallow directive to the robots.txt.
robots.txt (example)
User-Agent: * Allow: / Disallow: /logger/
Next place this code before the end < /body >tag on every page you want to track.
< script type="text/javascript" src="../logger/logger.php?t=< ? php echo time(); ? >&f=< ? php echo $_SERVER['REQUEST_URI']; ? >&r=< ? php echo urlencode($_SERVER["HTTP_REFERER"]); ? >">
Display Daily Hits with jQuery and Raphael.js
First make sure that you are including jquery.js and raphael.js files.
include(class.logger.php);
$log = new logger(); //Instentiate the class
$log->tablename = "logger"; //set logger table name
$log->dbconnect(); //connect to database
//set date and year text for the info bubble that appears on hover
$date = date('F')." ".date('Y');
//load raphael analytics javascript
//Parameters: "table[class], div[id], text[date], width, height, left gutter, bottom gutter, top gutter,stroke color, fontcolor, fill color, grid color
$log->loadraphael('data','holder',$date, 600, 250, 20, 30, 30,'#474747', '#000', '#eee', '#eee');
//load table hits containing data
//Parameters: month, year, div[id], table[class]
$log->dailyhits(11, 2009, 'holder', 'data');
(Optional) Example CSS file to position and size the "holder"
#holder {
width: 600px;
height: 450px;
left: 10px;
position: absolute;
top: 10px;
}
Display Hits Summary
//show total uniqe visitors to date(parameter: (int) number of months). For example: 3 will start counting from 3 monhts before today. echo $log->totalunique(3); //show total visits to date(parameter: (int) number of months). For example: 3 will start counting from 3 monhts before today. echo $log->totalhits(3); //visit details (parameter (int) number of last visits to display. For example :100 will show last 100 visits //the info is displayed in a table with visitdetails[class] for easy CSS styling. $log->visitdetails(100);
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
December 13th 2009
Mike - Give archive to download all code
apex - yup give the working code, this isn't working. There are too many error messages, so this is unusable.
January 24th 2010
maxmegalon - Thanks for the tutorial. There is a typo in logger.php, the last line should be $log->logvisit($browser, $ip, $host, $filevisited, $ref_domain); instead of $logger->logvisit($browser, $ip, $host, $filevisited, $ref_domain); Furthermore I was wondering whether it would make the code more readable and structured more logical if you were to include analytics.js etc and adding a start call instead of echoing them.
January 24th 2010
maxmegalon - There is a typo in the function create table. It contains the field 'host' twice. One of the fields should be 'filename'. I'm not sure whether this could be problematic, but in the function logvisit the key 'log_id' is not in the insert statement.
March 6th 2010
apex - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''logger' ( 'log_id' int(11) NOT NULL auto_increment, 'ip' varchar(16' at line 1
March 20th 2010
Aivis - Duplicate column name 'host' and in sql is error!
Emir - Aivis, I'll double check the code, re-post it and include .zip file soon.
July 24th 2010
Nik AF - The code presented here contains too much errors! However, after a few hours of tweaking, i was able to patch the code up and make it work! To see this in action, go to http://epay.pkns.gov.my (to increase the hit counter) and the look at http://epay.pkns.gov.my/main/dailyhits.php to see the graph.
November 23rd 2009 // PHP // Permalink
Drawing Shapes and Lines with PHP
Drawing shapes and lines with PHP is nothing like drawing with image editing program. Actually, when drawing with PHP you become the editing program. You use individual PHP functions to define colors, draw and fill shapes, re-size and save the image. These functions are part of the Thomas Boutell's GD graphics library that was bundled beginning with PHP version 4.3.0.
Drawing New Image
The basic function used to create a new image is called ImageCreate(). This function creates the canvas area for your new image. For example to create an image that is 300px wide and 300px high you would use following code:
$imageOne = ImageCreate(300, 300);Now that you have canvis you need to define colors you want to use in it. Colors are defined using RGB color system. Using decimal values from 0 to 255 for each of the red (R), green (G), and blue(B) you can define a specific color. The function used to define colors is ImageColorAllocate().
The first color you allocate is used as the background color of the image.
$white = ImageColorAllocate($imageOne, 255, 255, 255); $red = ImageColorAllocate($imageOne, 255, 0, 0); $blue = ImageColorAllocate($imageOne, 0, 0, 255); $green = ImageColorAllocate($imageOne, 0, 255, 0);
Drawing Lines and Shapes
There are several PHP functions to assist you in drawing lines and shapes. And as you can see below the function names are very descriptive.
- ImageEllipse() - to draw an ellipse
- ImageArc() - to draw arc (partial ellipse)
- ImagePolygon() - to draw a polygon
- ImageRectangle() - to draw a rectangle
- ImageLine() - to draw a line
Each of these functions use x-axis and y-axis coordinates as indicators of where to start and stop the drawing on the canvas. Here is sample of green rectangle that is 30px wide, 50px high and 10px from the left edge and 20px away from the top of the canvas.
ImageRectangle($imageOne, 10, 20, 40, 70, $green);

As you can see drawing with PHP requires some planning ahead.
Using a Color Fill
PHP can also fill the shapes with solid color. Functions to do that are:
- ImageFilledEllipse() - to fill an ellipse
- ImageFilledArc() - to fill a partial ellipse
- ImageFilledPlygon() - to fill a polygon
- ImageFilledRectangle() - to fill a rectangle
These functions are used just like nonfill drawing functions explained above.
ImageFilledRectangle($imageOne, 10, 20, 40, 70, $green);PHP comes with several built-in styles that are used in the display. For example IMG_ARC_PIE says to create a rounded edge. To learn more about styles in PHP visit: http://www.php.net/image.
Conclusion
I hope these basic functions help you understand image drawing in PHP. You can use dynamic data as part of these functions to create pie charts or even 3D charts. If you want to create JPEG and PNG files you will need to download and install some additional libraries. Here are some resources:
- JPEG library - ftp://ftp.uu.net/graphics/jpeg/
- PNG library - http://www.libpng.org/pub/png/libpng.html and zlib library http://www.zlib.net/
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
November 21st 2009 // PHP // Permalink
Simple PHP/MySQL authentication class
Here is a simple PHP/MySQL authentication script (class) that is secure and easy to use. The class features:
- Login form
- Password recovery with basic email injection protection
- Optional md5 password encryption
- MySQL logon table creation
- MySQL injection protection
- Page password protection
MySQL table
The only requirement for the table is that the username stores emails, because it is used for password recovery.
CREATE TABLE `logon` ( `userid` int(11) NOT NULL auto_increment, `useremail` varchar(50) NOT NULL default '', `password` varchar(50) NOT NULL default '', `userlevel` int(1) NOT NULL default '0', PRIMARY KEY (`userid`) ) TYPE=MyISAM
PHP Class (class.login.php)
IMPORTANT: Make sure to fill in the database info. See comments for the details.
//start session
session_start();
class logmein {
//database setup
//MAKE SURE TO FILL IN DATABASE INFO
var $hostname_logon = ' '; //Database server LOCATION
var $database_logon = ' '; //Database NAME
var $username_logon = ' '; //Database USERNAME
var $password_logon = ' '; //Database PASSWORD
//table fields
var $user_table = ''; //Users table name
var $user_column = ''; //USERNAME column (value MUST be valid email)
var $pass_column = ''; //PASSWORD column
var $user_level = ''; //(optional) userlevel column
//encryption
var $encrypt = false; //set to true to use md5 encryption for the password
//connect to database
function dbconnect(){
$connections = mysql_connect($this->hostname_logon, $this->username_logon, $this->password_logon) or die ('Unabale to connect to the database');
mysql_select_db($this->database_logon) or die ('Unable to select database!');
return;
}
//login function
function login($table, $username, $password){
$this->dbconnect();
//make sure table name is set
if($this->user_table == ""){
$this->user_table = $table;
}
//check if encryption is used
if($this->encrypt == true){
$password = md5($password);
}
//execute login via qry function that prevents MySQL injections
$result = $this->qry("SELECT * FROM ".$this->user_table." WHERE ".$this->user_column."='?' AND ".$this->pass_column." = '?';" , $username, $password);
$row=mysql_fetch_assoc($result);
if($row != "Error"){
if($row[$this->user_column] !="" && $row[$this->pass_column] !=""){
//register sessions
//you can add additional sessions here if needed
$_SESSION['loggedin'] = $row[$this->pass_column];
//userlevel session is optional. Use it if you have different user levels
$_SESSION['userlevel'] = $row[$this->user_level];
return true;
}else{
session_destroy();
return false;
}
}else{
return false;
}
}
//prevent injection
function qry($query) {
$this->dbconnect();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die(mysql_error());
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
}
//logout function
function logout(){
session_destroy();
return;
}
//check if loggedin
function logincheck($logincode, $user_table, $pass_column, $user_column){
$this->dbconnect();
//make sure password column and table are set
if($this->pass_column == ""){
$this->pass_column = $pass_column;
}
if($this->user_column == ""){
$this->user_column = $user_column;
}
if($this->user_table == ""){
$this->user_table = $user_table;
}
//exectue query
$result = $this->qry("SELECT * FROM ".$this->user_table." WHERE ".$this->pass_column." = '?';" , $logincode);
$rownum = mysql_num_rows($result);
//return true if logged in and false if not
if($row != "Error"){
if($rownum > 0){
return true;
}else{
return false;
}
}
}
//reset password
function passwordreset($username, $user_table, $pass_column, $user_column){
$this->dbconnect();
//generate new password
$newpassword = $this->createPassword();
//make sure password column and table are set
if($this->pass_column == ""){
$this->pass_column = $pass_column;
}
if($this->user_column == ""){
$this->user_column = $user_column;
}
if($this->user_table == ""){
$this->user_table = $user_table;
}
//check if encryption is used
if($this->encrypt == true){
$newpassword = md5($newpassword);
}
//update database with new password
$qry = "UPDATE ".$this->user_table." SET ".$this->pass_column."='".$newpassword."' WHERE ".$this->user_column."='".stripslashes($username)."'";
$result = mysql_query($qry) or die(mysql_error());
$to = stripslashes($username);
//some injection protection
$illigals=array("n", "r","%0A","%0D","%0a","%0d","bcc:","Content-Type","BCC:","Bcc:","Cc:","CC:","TO:","To:","cc:","to:");
$to = str_replace($illigals, "", $to);
$getemail = explode("@",$to);
//send only if there is one email
if(sizeof($getemail) > 2){
return false;
}else{
//send email
$from = $_SERVER['SERVER_NAME'];
$subject = "Password Reset: ".$_SERVER['SERVER_NAME'];
$msg = "Your new password is: ".$newpassword."
";
//now we need to set mail headers
$headers = "MIME-Version: 1.0 rn" ;
$headers .= "Content-Type: text/html; rn" ;
$headers .= "From: $from rn" ;
//now we are ready to send mail
$sent = mail($to, $subject, $msg, $headers);
if($sent){
return true;
}else{
return false;
}
}
}
//create random password with 8 alphanumerical characters
function createPassword() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
//login form
function loginform($formname, $formclass, $formaction){
$this->dbconnect();
echo'';
}
//reset password form
function resetform($formname, $formclass, $formaction){
$this->dbconnect();
echo'';
}
//function to install logon table
function cratetable($tablename){
$this->dbconnect();
$qry = "CREATE TABLE IF NOT EXISTS ".$tablename." (
userid int(11) NOT NULL auto_increment,
useremail varchar(50) NOT NULL default '',
password varchar(50) NOT NULL default '',
userlevel int(11) NOT NULL default '0',
PRIMARY KEY (userid)
)";
$result = mysql_query($qry) or die(mysql_error());
return;
}
//register function by Micah B-F.
function register($table, $username, $password){
//conect to DB
$this->dbconnect();
//make sure table name is set
if($this->user_table == ""){
$this->user_table = $table;
}
//check if encryption is used
if($this->encrypt == true){
$password = md5($password);
}
//execute registration via qry function that prevents MySQL injections
$result = $this->qry("INSERT INTO ".$this->user_table." VALUES(DEFAULT,'?','?',DEFAULT)", $username, $password);
$row=mysql_fetch_assoc($result);
if($row != "Error"){
if($row[$this->user_column] !="" && $row[$this->pass_column] !=""){
//register sessions
//you can add additional sessions here if needed
$_SESSION['loggedin'] = $row[$this->pass_column];
$_SESSION['username'] = $username;
//userlevel session is optional.
Use it if you have different user levels
$_SESSION['userlevel'] = $row[$this->user_level];
return true;
}else{
session_destroy();
return false;
}
}else{
return false;
}
}
}
Usage
This class can be used in many different scenarios, from traditional redirection to AJAX implementation.
Instantiate the Class
Make sure to include and instantiate the class on every page you use it.
include("class.login.php");
$log = new logmein(); //Instentiate the class
$log->dbconnect(); //Connect to the database
$log->encrypt = true; //set to true if password is md5 encrypted. Default is false.
Create Log on Table
Run this code only once to create the log on table.
include("class.login.php");
$log = new logmein();
$log->cratetable('logon');
Display Login Form
The login form takes in Class and ID parameters for easy styling with CSS, and form action parameter. If needed the form includes a hidden field "action" set to "log in".
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
//parameters here are (form name, form id and form action)
$log->loginform("loginformname", "loginformid", "form_action.php");
Display Password Reset Form
Just like the login form, the password reset form takes in Class, ID and form action parameters. If needed the form includes a hidden field "action" set to "resetlogin".
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
//parameters here are (form name, form id and form action)
$log->resetform("resetformname", "resetformid", "form_action.php");
Password Protect a Page
Place this code on top of every page you want to password protect.
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
//parameters are(SESSION, name of the table, name of the password field, name of the username field)
if($log->logincheck($_SESSION['loggedin'], "logon", "password", "useremail") == false){
//do something if NOT logged in. For example, redirect to login page or display message.
}else{
//do something else if logged in.
}
Login
Place this code inside the form action script. For example, in this tutorial I am using "form_action.php" as my form action script.
//instantiate if needed
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
if($_REQUEST['action'] == "login"){
if($log->login("logon", $_REQUEST['username'], $_REQUEST['password']) == true){
//do something on successful login
}else{
//do something on FAILED login
}
}
Log out
Place this code inside the script that is executed when user want's to log out.
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
//Log out
$log->logout();
//do something
Reset Password
Place this code inside the script that will run when password recovery is requested.
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
if($_REQUEST['action'] == "resetlogin"){
if($log->passwordreset($_REQUEST['username'], "logon", "password", "useremail") == true){
//do something on successful password reset
}else{
//do something on failed password reset
}
}
Download Class
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
December 14th 2009
jagoanweb - nicee... :) is reset password similar with change password?
Emir - Not really. Reset password generates a random password. A new function would need to be added for custom password change.
RandomUser - Excellent job and thank you for sharing!
December 30th 2009
chris - Will this run in mysql 4?
Emir - It should. Those are just some simple sql statements.
March 3rd 2010
kumar - hello sir, can pls send me a example created based on the above script . . i thnk u may understand wat iam asking am not getting the correct usage. . it will be help ful more if it is illustrated with example of writing.
March 3rd 2010
kumar - hello sir, can pls send me a example created based on the above script . . i thnk u may understand wat iam asking am not getting the correct usage. . it will be help ful more if it is illustrated with example of writing. my email-id is banothkumar@gmail.com i will be thankful to you. . .!!
March 6th 2010
dosen - hey man, can you provide working code in zip file in all of your posts because many of them dosn't work when they are copied of the screen.
March 17th 2010
Shafi - wow. this is what i was looking for. I'll need some tweeks. but no problem i'll manage it. I was just looking for the structure for proper .. can i use this code.?
March 29th 2010
hax - The code is very nice :) I have found just small bug which has to be changed in: include("class.login.php"); $log = new logmein(); $log->encrypt = true; //set encryption if($_REQUEST['action'] == "resetlogin"){ if($log->passwordreset($_REQUEST['username'], "logon, "password", "useremail") == true){ //do something on successful password reset }else{ //do something on failed password reset } } Sie logon has to be "logon",
Emir - Thanks for the note. I updated the code.
March 29th 2010
hax - Don't let cat to serve as a helper:) just small annotation.
Emir - Ha!! Tell me about it!
April 2nd 2010
Leo - Hi. I'd need to recognise which user is logged in, so is there a viariable I can recall to show his email address ? Thanks a lot.
August 9th 2010
Micah B-F - Thanks very much for this class! Simple, but perfect.
Here is a very basic registration function I added, which is basically the login function with a modified query.
//register function
function register($table, $username, $password){
//conect to DB
$this->dbconnect();
//make sure table name is set
if($this->user_table == ""){
$this->user_table = $table;
}
//check if encryption is used
if($this->encrypt == true){
$password = md5($password);
}
//execute registration via qry function that prevents MySQL injections
$result = $this->qry("INSERT INTO ".$this->user_table." VALUES(DEFAULT,'?','?',DEFAULT)", $username, $password);
$row=mysql_fetch_assoc($result);
if($row != "Error"){
if($row[$this->user_column] !="" && $row[$this->pass_column] !=""){
//register sessions
//you can add additional sessions here if needed
$_SESSION['loggedin'] = $row[$this->pass_column];
$_SESSION['username'] = $username;
//userlevel session is optional. Use it if you have different user levels
$_SESSION['userlevel'] = $row[$this->user_level];
return true;
}else{
session_destroy();
return false;
}
}else{
return false;
}
}
Emir - Thanks Micah, I added it to the class!
August 9th 2010
Johnny - The code looks great. I will implement this in my next project at http://www.codeberg.com/index.php
November 20th 2009 // PHP // Permalink
PHP Function to Generate HTML Table Using MySQL Database Data
Organize your MySQL database data in HTML tables created on the fly using this PHP function snippet. Function maketable uses MySQL query and an array of columns you want to display as attributes.
Function
function maketable($query, $fieldarray){
//count number of columns
$columns = count($fieldarray);
//run the query
$result = mysql_query($query) or die(mysql_error()) ;
$itemnum = mysql_num_rows($result);
if($itemnum > 0){
do{
echo "< tr >" ;
for($x = 0; $x < $columns; $x++){
echo "< td >" .$items[$fieldarray[$x]]. "< /td >" ;
}
echo "< /tr >" ;
}while($items = mysql_fetch_assoc($result));
}
}
Usage
echo "< table >";
$fieldarray = array("id","title","description");
maketable("SELECT * FROM bw_news", $fieldarray);
echo "< /table >";
Comments
April 28th 2010
Serdar - Thanks for the useful function. Line 6 in the function supposed to be like this $itemnum = mysql_num_rows($result);
Emir - Fixed. Thanks for catching this.
November 17th 2009 // PHP // Permalink
PHP/MySQL search engine script
Here is a quick tutorial/script to show you how to create PHP/MySQL search engine with search keywords displayed in bold.
List of some PHP functions used:- trim() - Strip whitespace (or other characters) from the beginning and end of a string
- explode() - Split a string by string
- array_unique() - Removes duplicate values from an array
- preg_replace() - Perform a regular expression search and replace
Save the file as search.php and upload it to your server.
See the commented sections for details.
< ?php
$hostname_logon = "localhost" ;
$database_logon = "databaseName" ;
$username_logon = "databaseUser" ;
$password_logon = "databasePass" ;
//open database connection
$connections = mysql_connect($hostname_logon, $username_logon, $password_logon) or die ( "Unabale to connect to the database" );
//select database
mysql_select_db($database_logon) or die ( "Unable to select database!" );
//specify how many results to display per page
$limit = 10;
// Get the search variable from URL
$var = @$_GET['q'] ;
$s = $_GET['s'] ;
//trim whitespace from the stored variable
$trimmed = trim($var);
//separate key-phrases into keywords
$trimmed_array = explode(" ",$trimmed);
// check for an empty string and display a message.
if ($trimmed == "") {
$resultmsg = "Search Error
Please enter a search...
" ;
}
// check for a search parameter
if (!isset($var)){
$resultmsg = "Search Error
We don't seem to have a search parameter!
" ;
}
// Build SQL Query for each keyword entered
foreach ($trimmed_array as $trimm){
// EDIT HERE and specify your table and field names for the SQL query
$query = "SELECT * FROM tablename WHERE field1 LIKE '%$trimm%' OR field2 like '%$trimm%' OR field3 like '%$trimm%' ORDER BY field1 DESC" ;
// Execute the query to get number of rows that contain search kewords
$numresults=mysql_query ($query);
$row_num_links_main =mysql_num_rows ($numresults);
// next determine if 's' has been passed to script, if not use 0.
// 's' is a variable that gets set as we navigate the search result pages.
if (empty($s)) {
$s=0;
}
// now let's get results.
$query .= " LIMIT $s,$limit" ;
$numresults = mysql_query ($query) or die ( "Couldn't execute query" );
$row= mysql_fetch_array ($numresults);
//store record id of every item that contains the keyword in the array we need to do this to avoid display of duplicate search result.
do{
$adid_array[] = $row[ 'fieldid' ];
}while( $row= mysql_fetch_array($numresults));
} //end foreach
if($row_num_links_main == 0 && $row_set_num == 0){
$resultmsg = "Search results for: ". $trimmed."
Sorry, your search returned zero results
" ;
}
//delete duplicate record id's from the array. To do this we will use array_unique function
$tmparr = array_unique($adid_array);
$i=0;
foreach ($tmparr as $v) {
$newarr[$i] = $v;
$i++;
}
// now you can display the results returned. But first we will display the search form on the top of the page
? >
< ?php
// display what the person searched for.
if( isset ($resultmsg)){
echo $resultmsg;
exit();
}else{
echo "Search results for: " . $var;
}
foreach($newarr as $value){
// EDIT HERE and specify your table and field names for the SQL query
$query_value = "SELECT * FROM tablename WHERE fieldid = '$value'";
$num_value=mysql_query ($query_value);
$row_linkcat= mysql_fetch_array ($num_value);
$row_num_links= mysql_num_rows ($num_value);
//now let's make the keywods bold. To do that we will use preg_replace function.
//Replace field
$titlehigh = preg_replace ( "'($var)'si" , " \1" , $row_linkcat[ 'field1' ] );
$linkhigh = preg_replace ( "'($var)'si" , " \1" , $row_linkcat[ 'field2' ] );
$linkdesc = preg_replace ( "'($var)'si" , " \1" , $row_linkcat[ 'field3' ] );
foreach($trimmed_array as $trimm){
if($trimm != 'b' ){
$titlehigh = preg_replace( "'($trimm)'si" , " \1" , $titlehigh);
$linkhigh = preg_replace( "'($trimm)'si" , " \1" , $linkhigh);
$linkdesc = preg_replace( "'($trimm)'si" , " \1" , $linkdesc);
}
//end highlight
? >
< ?php echo $titlehigh; ? > < ?php echo $linkhigh; ? > < ?php echo $linkdesc; ? >
< ?php } //end foreach $trimmed_array if($row_num_links_main > $limit){ // next we need to do the links to other search result pages if ($s>=1) { // do not display previous link if 's' is '0' $prevs=($s-$limit); echo "Here are some helpfull resources:
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
November 18th 2009
barney0o0 - Ive have used this and when the search is sucessful its fine...however when no search results are found, the script suddenly ends and removes all following divs etc from the page
Ross Waycaster - Yeah remove exit(); and add another { after }else{ on line 82 and then add another } at the very end of the script before ?> I think it's like 132.. Hope this helps.. There are some weird errors in this script like the spaces in the html and php tags??? why? And on the preg_replace lines it's \\1 not //1 Other than that it's a great script thanks! I got it working for me like a charm!
February 4th 2010
zoran zaric - Emire jel razumijes ovaj jezik?
Emir - Razumijem Zorane! Pozdrav...
February 7th 2010
Pedro - I think line 113 should be $linkdesc instead of $linkhigh
Emir - You are right. I corrected it.
March 8th 2010
Brian - I'm getting a error on line 122 Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';'
March 19th 2010
fisconion - Hey. I have this error: Parse error: syntax error, unexpected T_VARIABLE in /pages/xx/xx/htdocs/xxx/webapp/search.php on line 7 Greetings
- @Brian I'm getting the same error: Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in /var/www/html/chris/playground/simple_search/search.php on line 122 There seems to be ;'s at the end of the lines though?
April 22nd 2010
Wow - I was going to take a look at your authentication class until I saw the DUMPTRUCK sized security holes in this script! People who download this this will use it as is - and get creamed with SQL injection attacks.
June 7th 2010
dong - I CAN NOT run your code I hope we can talk in skype my skype is chinabelarus1 I need to search in my database like google
August 26th 2010
- where this does code go to: < ?php echo $q; ? > its line 072: can anyone explain?? thanks
November 9th 2009 // PHP // Permalink
Manipulating Strings with PHP
PHP provides many functions to manipulate strings. Here are some of the more common once.
Getting the Length of a String
strlen(s) - returns the length of the string specified as the argument
$s = "Sample String"; $len = strlen($s);
Trimming White-space from a String
White-space characters are: space, tab and linefeed that have no visual representation.
ltrim(s) - returns the value of string with white-space trimmed from the left end
rtrim(s) - returns the value of string with white-space trimmed from the right
trim(s) - returns the value of string with white-space trimmed from both end.
$s = "Sample string"; $new = ltrim($s); // returns "Sample string" $new = rtrim($s); // returns "Sample string" $new = trim($s); // returns "Sample string"
Converting Strings to Upper or Lowercase
strtoupper(s) - returns the value of it's argument, converted to all uppercase
strtolower(s) - returns the value of it's argument, converted to all lowercase
$s = "Sample string"; $new = strtoupper($s); // returns "SAMPLE STRING" $new = strtolower($s); // returns "sample string"
Comparing Strings
strcasecmp(s1,s2) - Case-insensitive comparison. Returns -1 if s1 is less then s2; 1 if s1 is greater then s2; 0 if they match.
strcmp(s1, s2) - Case-sensitive comparison. Returns -1 if s1 is less then s2; 1 if s1 is greater then s2; 0 if they match.
strncasecmp(s1,s2, n) - Case-insensitive comparison. Returns -1 if s1 is less then s2; 1 if s1 is greater then s2; 0 if they match. The maximum of n characters is included in the comparison. NOTE: this function was added in PHP version 4.0.2.
strncmp(s1, s2, n) - Case-sensitive comparison. Returns -1 if s1 is less then s2; 1 if s1 is greater then s2; 0 if they match. The maximum of n characters is included in the comparison.
Comments
No Comments
November 8th 2009 // PHP // Permalink
Add or delete HTML table rows from an .html file using PHP
ProblemI worked on a PHP project where I needed to add and delete rows from an HTML table located in a simple .html file without any database support. The data for the table was provided by a web service. My HTML table looked something like this:
| Id | Name | Action |
|---|---|---|
| 2 | John |
delete |
| 3 | Max |
delete |
Solution
- Write HTML table to a file and surround each row with HTML comments containing unique id.
- Use preg_replace function to find the row surrounded with unique comment and modify it.
How to...
First I had to figure out the file structure. In my case I needed three files:
- file that contains the table
- file to display table
- file that executs requests.
1. File that contains the table
Knowing that with PHP I can append text at the end of file, I needed to create an HTML table that would allow me to add rows to it. Here is what I came up with:
Filename: table_include.html
| Column one | Column two |
|---|
Notice the comment about not including closing "TBODY" and "TABLE" tags.
2. File that displays table.
The table needed to be displayed in a "DIV" element.
File name: my_table.php
echo ''; include("table_include.html"); echo '';
Using PHP include function, I am including table_include.html file and completing table code by adding and below the include. In my case the table rows were generated dynemically as part of a different process. But one important part of the table row generating script was to surround each row with an HTML comment containing a uniqe string. I chose to use PHP's time() function for unique code. The table code looked something like this:
$rowid = time(); $table_row = 'delete rowColumn two content';
3. File that executes requests
See comments for details. File name: execute.php
switch ($_REQUEST["action"]){
case 'add':
//place the code that adds rows here.
//maybe the values for each row are submitted with a form
//for this tutorial I am using a loop to add five rows
for($i=0;$i<5;$i++){
//HTML table markup surrounded with comments
$rowid = time();
$table_row = '< a href="execute.php?action=delete&id=">delete row< /a >Column two content';
//Write the row to "table_include.html" using append "a" parametar
if (!$file_handle = fopen("table_include.html","a")) {
$error = "Cannot open file";
}
if (fwrite($file_handle, $table_row) === FALSE) {
$error = "Cannot write to file";
}
fclose($file_handle);
sleep(1); // we need to have a small pause for generating unique id with PHP time() function. Damn PHP is so fast. :)
}
break;
case 'delete':
$parameter = '';
$filename = "table_include.html";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
//replace pattern that looks for our $parametar and everything in-between
$replace = "%($parameter)(.*?)($parameter)%is";
//use preg_replace to delete the row found using $parameter pattern
$myNewText = preg_replace($replace, "", $contents);
//write updated table code to "table_include.html"
$filename = "table_include.html";
if (!$file_handle = fopen($filename,"w")) {
$error = "Cannot open file";
}
if (!fwrite($file_handle, $myNewText)) {
$error = "Cannot write to file";
}
fclose($file_handle); // close file
//redirect to the table display file
header("Location: my_table.php");
break;
}
Suggestion
One would be to use AJAX to call execute.php file. In the application I was working on I used jQuery for my AJAX functions.
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.

Comments
February 22nd 2010
umang - copied from http://www.bewebmaster.com/228.php
Reply
February 23rd 2010
Emir - You are right in a way. I actually own BeWebmaster.com. That is my old website that I am not updating anymore. I moved the content to this one. I appreciate you posting the comment. That particular page has been copied by others and called their own before.
Shafi - really really wanna appreciate you. nice work. I am using these codes.. hope u dont mind.
Talifhani Luvhengo - This is kinda funny. Talk about egg on your face. Good article.
Reply
July 8th 2010
Hari K T - Great post . Thanks for your great solution. I loved it , but didn't love this piece :) . I hope you too may not love once you see the solution below . I hacked some to make it . Your code : //set counters $npos = 0; $sstl = 0; //a simple for loop with modulus operator will help us separate styles from selectors. for($i = 0; $i<$size; $i++){ if ($i % 2 == 0) { $selectors[$npos] = $sarray[$i]; $npos++; }else{ $sstyles[$sstl] = $sarray[$i]; $sstl++; } } I hacked to for( $i = 0 ; $i < $size; $i++ ){ $selectors[$i] = $sarray[$i*2]; $sstyles[$i] = $sarray[$i * 2 + 1]; } Thanks Hari K T http://harikt.com
Reply