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

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; read more

Related Posts:

  • No Related Posts

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. read more

Related Posts:

  • No Related Posts

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("rn", "n", "r"); //Processes rn'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; } } } read more

Related Posts:

  • No Related Posts

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 (
              	logid INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
				ip VARCHAR( 16 ) NOT NULL ,
				host VARCHAR( 100 ) NOT NULL ,
				visitdate DATETIME NOT NULL ,
				visitedpage VARCHAR(255) NOT NULL ,
				referring VARCHAR( 255 ) NOT NULL
            )

PHP Class (class.logger.php)

IMPORTANT: Make sure to fill in the database info. See comments for the details.

<?php //start session class logger { //database setup var $hostname_logon = 'localhost'; //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, $referring){ //check if ip is filtered if(!in_array($ip,$this->filter)){ $qry = "INSERT INTO ".$this->tablename." (ip, host, visitdate, visitedpage, referring)VALUES('".$ip."','".$host."',NOW(), '".$filename."', '".$referring."' )"; $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> <tr>'; for($x=1;$x<=$numdaysinmonth;$x++){ echo '<th>'.$x.'</th>'; } echo '</tr> </tfoot> <tbody> <tr>'; $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 '<td>'; echo $numrows; $totalhits = $totalhits + $numrows; echo '</td>'; } echo '</tr> </tbody> </table> <div id="'.$div.'"></div>'; } //display visit details (parameter (int) number of last visits to display function visitdetails($num){ $qry = "SELECT * FROM ".$this->tablename." WHERE visitdate!='' ORDER BY logid 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><tr><th>IP</th><th>Host</th><th>Referring Page</th><th>Page Visited</th><tr></thead>'; echo '<tbody>'; while ($row = mysql_fetch_object($result)){ $nowww = ereg_replace('www.','',$row->referring); $domain = parse_url($nowww); if(!empty($domain["host"])) { $host = $domain["host"]; } echo '<tr><td>'.$row->ip.'</td> <td>'.$row->host.'</td> <td><a href="'.$row->referring.'" target="_blank">'.$host.'</a></td> <td><a href="..'.$row->filename.'" target="_blank">'.$row->filename.'</a></td> </tr>'; } 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,$raphael_path){ //load latest jquery. Uncomment if you are already using jquery. echo '<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>'; echo '<script type="text/javascript" src="'.$raphael_path.'"></script><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 createtable($tablename){ $qry = "CREATE TABLE IF NOT EXISTS ".$tablename." ( logid INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , ip VARCHAR( 16 ) NOT NULL , host VARCHAR( 100 ) NOT NULL , visitdate DATETIME NOT NULL , visitedpage VARCHAR(255) NOT NULL , referring VARCHAR( 255 ) NOT NULL )"; $result = mysql_query($qry) or die(mysql_error()); return; } } ?> read more

Related Posts:

  • No Related Posts

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. read more

Related Posts:

  • No Related Posts

Simple PHP/MySQL authentication/login class

Here is a simple PHP/MySQL authentication/login 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.

<?php //For security reasons, don't display any errors or warnings. Comment out in DEV. error_reporting(0); //start session session_start(); class logmein { //database setup //MAKE SURE TO FILL IN DATABASE INFO var $hostname_logon = 'localhost'; //Database server LOCATION var $database_logon = ''; //Database NAME var $username_logon = ''; //Database USERNAME var $password_logon = ''; //Database PASSWORD //table fields var $user_table = 'logon'; //Users table name var $user_column = 'useremail'; //USERNAME column (value MUST be valid email) var $pass_column = 'password'; //PASSWORD column var $user_level = 'userlevel'; //(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){ //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 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){ //conect to DB $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){ //conect to DB $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_db = md5($newpassword); }else{ $newpassword_db = $newpassword; } //update database with new password $qry = "UPDATE ".$this->user_table." SET ".$this->pass_column."='".$newpassword_db."' WHERE ".$this->user_column."='".stripslashes($username)."'"; $result = mysql_query($qry) or die(mysql_error()); $to = stripslashes($username); //some injection protection $illegals=array("%0A","%0D","%0a","%0d","bcc:","Content-Type","BCC:","Bcc:","Cc:","CC:","TO:","To:","cc:","to:"); $to = str_replace($illegals, "", $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; \r\n" ; $headers .= "From: $from \r\n" ; //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){ //conect to DB $this->dbconnect(); echo' <form name="'.$formname.'" method="post" id="'.$formname.'" class="'.$formclass.'" enctype="application/x-www-form-urlencoded" action="'.$formaction.'"> <div><label for="username">Username</label> <input name="username" id="username" type="text"></div> <div><label for="password">Password</label> <input name="password" id="password" type="password"></div> <input name="action" id="action" value="login" type="hidden"> <div> <input name="submit" id="submit" value="Login" type="submit"></div> </form> '; } //reset password form function resetform($formname, $formclass, $formaction){ //conect to DB $this->dbconnect(); echo' <form name="'.$formname.'" method="post" id="'.$formname.'" class="'.$formclass.'" enctype="application/x-www-form-urlencoded" action="'.$formaction.'"> <div><label for="username">Username</label> <input name="username" id="username" type="text"></div> <input name="action" id="action" value="resetlogin" type="hidden"> <div> <input name="submit" id="submit" value="Reset Password" type="submit"></div> </form> '; } //function to install logon table function cratetable($tablename){ //conect to DB $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; } } ?> read more

Related Posts:

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 >"; read more

Related Posts:

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 = mysql_real_escape_string(@$_REQUEST['q']); //get pagination $s = mysql_real_escape_string($_REQUEST['s']); //set keyword character limit if(strlen($var) < 3){ $resultmsg = "<p>Search Error</p><p>Keywords with less then three characters are omitted...</p>" ; } //trim whitespace from the stored variable $trimmed = trim($var); $trimmed1 = trim($var); //separate key-phrases into keywords $trimmed_array = explode(" ",$trimmed); $trimmed_array1 = explode(" ",$trimmed1); // check for an empty string and display a message. if ($trimmed == "") { $resultmsg = "<p>Search Error</p><p>Please enter a search...</p>" ; } // check for a search parameter if (!isset($var)){ $resultmsg = "<p>Search Error</p><p>We don't seem to have a search parameter! </p>" ; } // 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 // MySQL "MATCH" is used for full-text searching. Please visit mysql for details. $query = "SELECT * , MATCH (field1, field2) AGAINST ('".$trimm."') AS score FROM table_name WHERE MATCH (field1, field2) AGAINST ('+".$trimm."') ORDER BY score 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); //If MATCH query doesn't return any results due to how it works do a search using LIKE if($row_num_links_main < 1){ $query = "SELECT * FROM table_name WHERE field1 LIKE '%$trimm%' OR field2 LIKE '%$trimm%' ORDER BY field3 DESC"; $numresults=mysql_query ($query); $row_num_links_main1 =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[ 'field_id' ]; }while( $row= mysql_fetch_array($numresults)); } //end foreach //Display a message if no results found if($row_num_links_main == 0 && $row_num_links_main1 == 0){ $resultmsg = "<p>Search results for: ". $trimmed."</p><p>Sorry, your search returned zero results</p>" ; } //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++; } //total result $row_num_links_main = $row_num_links_main + $row_num_links_main1; // now you can display the results returned. But first we will display the search form on the top of the page echo '<form action="search.php" method="get"> <div> <input name="q" type="text" value="'.$q.'"> <input name="search" type="submit" value="Search"> </div> </form>'; // display an error or, what the person searched if( isset ($resultmsg)){ echo $resultmsg; }else{ echo "<p>Search results for: <strong>" . $var."</strong></p>"; foreach($newarr as $value){ // EDIT HERE and specify your table and field unique ID for the SQL query $query_value = "SELECT * FROM newsight_articles WHERE field_id = '".$value."'"; $num_value=mysql_query ($query_value); $row_linkcat= mysql_fetch_array ($num_value); $row_num_links= mysql_num_rows ($num_value); //create summary of the long text. For example if the field2 is your full text grab only first 130 characters of it for the result $introcontent = strip_tags($row_linkcat[ 'field2']); $introcontent = substr($introcontent, 0, 130)."..."; //now let's make the keywods bold. To do that we will use preg_replace function. //Replace field $title = preg_replace ( "'($var)'si" , "<strong>\\1</strong>" , $row_linkcat[ 'field1' ] ); $desc = preg_replace ( "'($var)'si" , "<strong>\\1</strong>" , $introcontent); $link = preg_replace ( "'($var)'si" , "<strong>\\1</strong>" , $row_linkcat[ 'field3' ] ); foreach($trimmed_array as $trimm){ if($trimm != 'b' ){ $title = preg_replace( "'($trimm)'si" , "<strong>\\1</strong>" , $title); $desc = preg_replace( "'($trimm)'si" , "<strong>\\1</strong>" , $desc); $link = preg_replace( "'($trimm)'si" , "<strong>\\1</strong>" , $link); }//end highlight }//end foreach $trimmed_array //format and display search results echo '<div class="search-result">'; echo '<div class="search-title">'.$title.'</div>'; echo '<div class="search-text">'; echo $desc; echo '</div>'; echo '<div class="search-link">'; echo $link; echo '</div>'; echo '</div>'; } //end foreach $newarr 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 '<div class="search_previous"><a href="'.$PHP_SELF.'?s='.$prevs.'&q='.$var.'">Previous</a> </div>'; } // check to see if last page $slimit =$s+$limit; if (!($slimit >= $row_num_links_main) && $row_num_links_main!=1) { // not last page so display next link $n=$s+$limit; echo '<div class="search_next"><a href="'.$PHP_SELF.'?s='.$n.'&q='.$var.'">Next</a> </div>'; } }//end if $row_num_links_main > $limit }//end if search result ?> read more

Related Posts:

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. read more

Related Posts:

Add or delete HTML table rows from an .html file using PHP

Problem

I 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

  1. Write HTML table to a file and surround each row with HTML comments containing unique id.
  2. 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:

  1. file that contains the table
  2. file to display table
  3. 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; } read more

Related Posts:

Page 1 of 212
© Copyright Emir Plicanic - Theme by Pexeto