Languages and Tools


What is CSS?

CSS is a simple file which controls the visual appearance of a Web page without compromising its structure. Using CSS we can control our font size, font color, link color and many other attributes on our web page. This will make our HTML code much more readable and the page size will be reduced.

Why to use it and how to use it properly

If you don’t use CSS on your web pages and you have many tables and content on them, chances are that your HTML file size will be quite big. Fact is that we live in a busy world, and people are not will to wait more than 5 seconds web page to load.

From the other side some web developers implement the CSS on wrong way. They write their CSS in HTML code of the page, like this:

<html>
<head>
<title>My Page</title>
<style>
A
	{
	font-family: Verdana;
	font-size:8pt;
	color:black;
	text-decoration:none
	}
</style>
…..

What is wrong with this technique? Well, imagine that you have site with more than 50 pages. One day, you decide that you want to change font color and colors of the links on your site. You will have to edit ALL the pages on your site, and do to that you will need time, because you place your CSS in your web page.

Better way is to save your visual attributes in separate, external CSS file, and to link that file with your page like this:

<html>
<head>
<title>My Page</title>
<link href="myStyle.css" rel="stylesheet" type="text/css">
….

Using this technique, you can change the look of your site within minutes, regardless of the number of pages, because your visual attributes are saved in ONE external CSS file. Edit that file, and you are done.

Benefits

Which are the benefits of using CSS? List is quite long and I will list here only the most important.

  • Your web page will load faster
  • Web page will become more search engine friendly
  • You can change you site appearance within minutes
  • You can write separate CSS file for handheld devices which will be called up instead of the regular CSS file
  • You can forget about creating printer friendly version of your site using separate CSS file when user chooses to print the web page.

Avoiding standard HTML commands like:

<font color="#0000ff"><font size=2>Product</font></font></font>

will help us to reduce file size, but that is not the only benefit. Using CSS word product in this example will be moved more close on the top of the document. Search engine will pick up more content and less code.

Imagine that you have 3 columns table on your page. When you see the code, you will notice that first come code for your table, and after that it come your content. Positioning your 3 columns using CSS instead of standard inline elements:

<table width="90%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="381" height="150" valign="top" bgcolor="FFEDD4">
My Product
</td>
    <td height="150" valign="top" bgcolor="FFEDD4">
…..

When CSS is used, your code might look like this:

<div id="leftcontent">
My Product
</div>

Again your code is much more clear, and your content is moved on the top of your document, making your HTML page search engine friendly, and reducing your file size.

Content is one of the most important factors in Search Engine Optimization, and you will benefit with removing the unnecessary code in your HTML and create search engine friendly web page.

Validate it

Browser war is far behind us. Reality is that most of the people today use Internet Explorer, but you should try to be on safe side and ensure that your CSS code is valid. Not all browsers interpret the CSS on same way. You can validate your CSS here: http://jigsaw.w3.org/css-validator/

About The Author

Zoran Makrevski is founder and CEO of SEO.Goto.gr.
Since 1998 has focused on E-Commerce and attempts to bring more traffic to the customer sites bring him in the SEO industry, and he is running his own company today.
Search Engine Positioning Firm
SEO.Goto.gr

See how you can create graphic effects on text with PHP and GD – drop shadows, arcs, fonts and colors.

Problem

A-tec Signs and Sraphics Inc. launched a web site with the idea to sell decals online. To achieve better customers ineterest the website had to integrate online decal builder. The company is offering also decals for vehicles which brought some specific requirements to the builder like having the decal text turning arround 4 types of arcs.

Goals

  • Provide users with preview area
  • Allow visitors to choose font and color
  • Allow adding drop shadow and selecting drop shadow color
  • Allow turning the text into arcs
  • Real Time calculating

Solution

Because of the need for increasing customers interest we had to think about not for perfect math formulas when showing the graphs in the preview area, but for the people who will look at them.

As we will reaveal below, there were few problems going arround human appreceptions for something ‘perfectly smooth’ and the matchematical perfect figures.

Methodology

We were going to extensively use PHP GD library for the text effects. It provided easy changing of fonts and colors, adding drop shawdows and rotating the texts.

We had also to create color palletes which to appear when user click and disappear when color is selected (You can personally try the decals creating here). Using hidden layers and javascript was supposed to do the work.

The main problem in this site was to create 4 types of arcs so when the user selects one of them the text is created arround imaginary arc (like in the vector graphical softwares). We were going to study Bezie’s formulas and create these arcs with its help.

Implementation

PIM Team Bulgaria had the task to build the full functional online decals builder with the following features:

- Decal background

Some users were supposed to have their decals placed on colored background. We had to allow the preview area to be painted in a selected background. First we created the image in temp folder:

  // the name of destination image
  $dest='decals/'.time().'.jpg';

  //the background
  imagefilledrectangle ( $im, 0, 0, 590, 60, $colors[$_POST['bcolors']]);

$colors array contains the available color which are stored by the administrator in the database.

Thus, when the visitor selects a background it is passed as parametter to imagefilledrectangle function.

- Font selection

Users should be able to select fonts for their future decals. Knowing that we can’t consider all the fonts will be available on all visitor’s computers we had to upload them on the web server directory.

We allowed the admin to manage the fonts, adding their names and uploading files in admin area.

The fonts in the select box came from the database. Selected font was passed in the call to imagettftext funtion which is drawing on the previously created image.

- Color Selections

The color selections had to be a palettes which appear when user clicks and disappear when color is selected. The palette had to look as a table with colors and these colors are also defined in the

admin area so they had to come dynamicly. We had to seed a static javascript function with dynamic content.

We created a PHP cycle which was taking the colors from the database and then creating a string for HTML table. This table is then passed to a javascript function which creates the palletes with the help of hidden layers:

  function showTable(table)
{
   mouseX = window.event.x + document.body.scrollLeft+25;

   if(table=='background')
   {
      var content="";
      var y=460;
   }

   if(table=='fonts')
   {
      var content="";
      var y=690;
   }

   if(table=='shadows')
   {
      var content="";
      var y=810;
   }

   document.getElementById('tabler').style.pixelLeft=mouseX;
   document.getElementById('tabler').style.pixelTop=y;
   document.getElementById('tabler').style.visibility='visible';
   document.getElementById('tabler').innerHTML=content;
}

Of course, once the user select the desired color we had to hide the pallette:

  function setColor(elid,color,fromid,shc)
{

   document.getElementById(elid).value=color;
   document.getElementById('tabler').style.visibility='hidden';

}

Thus we created nice palettes which appear and disappear on a single click and don’t take much space on the screen.

- Drop Shawdows

The decals offered has the ability to have a drop shadow added so we had to add this option to the online builder. PHP however didn’t offered a nice function for that. We created a procedure which draws the texts twice – once the original 100% saturated text and once the shadow with a percentage of the color and appropriate displacement. Of course the shadow was drawn on the image before the main text.

 @imagettftext($img, 20, $gr[$i], $x+$dx, $ys[$i]+$dy, $scolors[$shadowcolor], "fonts/".$_POST['fonts'],$word[$i]);

- Arcs

The main problem came when we had to ‘rotate’ the texts thru arcs. First we created perfect Bezie funtion which to draw the curves and adjust the letter above them. But what a surprise – the curves looked perfect alone, but when we adjusted the letters above them they seemed rough.

After studying this problem we realised that the rough screen resolution and the disability to antialise the images wouldn’t allow us to create nice arcs. We were standing against insoluble problem.

We decided to create few arcs with a graphical software (CorelDraw) and to see what could be wrong.

We noticed that Corel’s curves were looking great after they are manually adjusted. However you can’t just leave the program to create perfect curves automaticly. A human eye was needed to judge when a curve looks right and when not.

We got a totally different direction. There wasn’t an universal function to help us. The solution we found was to ‘manually’ adjust each letter. We created a procedure with cases which were adjusting each letter on the appropriate place and with appropriate rotation depending on how long was the text. It worked!

We created 2 arrays for each arc type – one array with the positions and one array with the rotations.

The rest was simple:

	if($arctype)
  {
    $start=(35-$l)/2;
    if($start%2) $start+=1;
    $gr=array_slice($gr,$start,$l);
    $ys=array_slice($ys,$start,$l);
  }  

 if(!$arctype)
 {
    $ys=array();
     $gr=array();
    //making the arrays
    for($i=0;$i

You can go on the atec’s site and try the arcs we achieved (http://atecsigns.com/decal/step_1.php).

Results

Now A-tec Sings’s web builder creates perfect decals with graphs, calculates the price and allows you to add the decals to your shopping cart and chgeckout (the shopping cart software is also created by PIM Team Bulgaria).

The builder allows the visitor to create the desired decals with any color, dropped shadow, background and shape, to preview it and to calculate the cost for different sizes and quantities.

The website and builder were promoted with massive radio advertising company. At that time it was the only decal builder which allowed creating texts arround arcs.

Conclusions

  • Use GD to create text effects
  • Do not forget that you can create you own functions for what GD does not offer
  • Do not always search for math perfect formulas. The graphical effects are intended to the human eye
  • Load fonts in the server
  • Use javascript and hidden layers to achieve great flexibility

About The Author

Bobby Handzhiev is a senior developer in PIM Team Bulgaria
http://pimteam.net
admin@pimteam.net

Installment 1

Developing State-enabled Applications With PHP

When a user is browsing through a website and is surfing from one web page to another, sometimes the website needs to remember the actions (e.g. choices) performed by the user. For example, in a website that sells DVDs, the user typically browses through a list of DVDs and selects individual DVDs for check out at the end of the shopping session. The website needs to remember which DVDs the user has selected because the selected items needs to be presented again to the user when the user checks out. In other words, the website needs to remember the State – i.e. the selected items – of the user’s browsing activities.

However, HTTP is a Stateless protocol and is ill-equipped to handle States. A standard HTML website basically provides information to the user and a series of links that simply directs the user to other related web pages. This Stateless nature of HTTP allows the website to be replicated across many servers for load balancing purposes. A major drawback is that while browsing from one page to another, the website does not remember the State of the browsing session. This make interactivity almost impossible.

In order to increase interactivity, the developer can use the session handling features of PHP to augment the features of HTTP in order to remember the State of the browsing session. The are basically 2 ways PHP does this:

  1. Using cookies
  2. Using Sessions

The next installment discusses how to manage sessions using cookies…

Installment 2

Cookies

Cookies are used to store State-information in the browser. Browsers are allowed to keep up to 20 cookies for each domain and the values stored in the cookie cannot exceed 4 KB. If more than 20 cookies are created by the website, only the latest 20 are stored. Cookies are only suitable in instances that do not require complex session communications and are not favoured by some developers because of privacy issues. Furthermore, some users disable support for cookies at their browsers.

The following is a typical server-browser sequence of events that occur when a cookie is used:

  1. The server knows that it needs to remember the State of browsing session
  2. The server creates a cookie and uses the Set-Cookie header field in the HTTP response to pass the cookie to the browser
  3. The browser reads the cookie field in the HTTP response and stores the cookie
  4. This cookie information is passed along future browser-server communications and can be used in the PHP scripts as a variable

PHP provides a function called setcookie() to allow easy creation of cookies. The syntax for setcookie is:

int setcookie(string name, [string val], [int expiration_date], [string path], string domain, [int secure])

The parameters are:

  1. name – this is a mandatory parameter and is used subsequently to identify the cookie
  2. value – the value of the cookie – e.g. if the cookie is used to store the name of the user, the value parameter will store the actual name – e.g. John
  3. expiration_date – the lifetime of the cookie. After this date, the cookie expires and is unusable
  4. path – the path refers to the URL from which the cookie is valid and allowed
  5. domain – the domain the created the cookie and is allowed to read the contents of the cookie
  6. secure – specifies if the cookie can be sent only through a secure connection – e.g. SSL enable sessions

The following is an example that displays to the user how many times a specific web page has been displayed to the user. Copy the code below (both the php and the html) into a file with the .php extension and test it out.

[?php
//check if the $count variable has been associated with the count cookie
if (!isset($count)) {
    $count = 0;
} else {
    $count++;
}
setcookie("count", $count, time()+600, "/", "", 0);
?]

[html]
    [head]
        [title]Session Handling Using Cookies[/title]
    [/head]
    [body]
        This page has been displayed: [?=$count ?] times.
    [/body]
[/html]

The next installment discusses how to manage sessions using PHP session handling functions with cookies enabled…

Installment 3

PHP Session Handling – Cookies Enabled

Instead of storing session information at the browser through the use of cookies, the information can instead be stored at the server in session files. One session file is created and maintained for each user session. For example, if there are three concurrent users browsing the website, three session files will be created and maintained – one for each user. The session files are deleted if the session is explicitly closed by the PHP script or by a daemon garbage collection process provided by PHP. Good programming practice would call for sessions to be closed explicitly in the script.

The following is a typical server-browser sequence of events that occur when a PHP session handling is used:

  1. The server knows that it needs to remember the State of browsing session
  2. PHP generates a sssion ID and creates a session file to store future information as required by subsequent pages
  3. A cookie is generated wih the session ID at the browser
  4. This cookie that stores the session ID is transparently and automatically sent to the server for all subsequent requests to the server

The following PHP session-handling example accomplishes the same outcome as the previous cookie example. Copy the code below (both the php and the html) into a file with the .php extension and test it out.

[?php //starts a session session_start(); //informs PHP that count information needs to be remembered in the session file if (!session_is_registered("count")) { session_register("count"); $count = 0; } else { $count++; } $session_id = session_id(); ?] [html] [head] [title]PHP Session Handling – Cookie-Enabled[/title] [/head] [body] The current session id is: [?=$session_id ?] This page has been displayed: [?=$count ?] times. [/body] [/html]


A summary of the functions that PHP provides for session handling are:

  1. boolean start_session() – initializes a session
  2. string session_id([string id]) – either returns the current session id or specify the session id to be used when the session is created
  3. boolean session_register(mixed name [, mixed ...]) – registers variables to be stored in the session file. Each parameter passed in the function is a separate variable
  4. boolean session_is_registered(string variable_name) – checks if a variable has been previously registered to be stored in the session file
  5. session_unregister(string varriable_name) – unregisters a variable from the session file. Unregistered variables are no longer valid for reference in the session.
  6. session_unset() – unsets all session variables. It is important to note that all the variables remain registered.
  7. boolean session_destroy() – destroys the session. This is opposite of the start_session function.

The next installment discusses how to manage sessions using PHP session handling functions when cookies are disabled…

Installment 4

PHP Session Handling – Without Cookies

If cookies are disabled at the browser, the above example cannot work. This is because although the session file that stores all the variables is kept at the server, a cookie is still needed at the browser to store the session ID that is used to identify the session and its associated session file. The most common way around this would be to explicitly pass the session ID back to the server from the browser as a query parameter in the URL.

For example, the PHP script generates requests subsequent to the start_session call in the following format:

http://www.yourhost.com/yourphpfile.php?PHPSESSID=[actual session ID]

The following are excerpts that illustrate the discussion:

Manually building the URL:

$url = “http://www.yoursite.com/yourphppage.php?PHPSESSID=” . session_id();
[a href="[?=$url ?]“]Anchor Text[/a]

Building the URL using SID:

[a href="http://www.yoursite.com/yourphppage.php?[?=SID ?]“]Anchor Text[/a]

About The Author

John L is the webmaster of http://www.bimmercenter.com..

daboss@bimmercenter.com

Most interactive websites nowadays require data to be presented dynamically and interactively based on input from the user. For example, a customer may need to log into a retail website to check his purchasing history. In this instance, the website would have stored two types of data in order for the customer to perform the check – the customer’s personal login details; and the customer’s purchased items. This data can be stored in two types of storage – flat files or databases.

Flat files are only feasible in very low to low volume websites as flat files have 3 inherent weaknesses:

  1. The inability to index the data. This makes it necessary to potentially read ALL the data sequentially. This is a major problem if there are a lot of records in the flat file because the time required to read the flat file is proportionate to the number of records in the flat file.
  2. The inability to efficiently control access by users to the data
  3. The inefficient storage of the data. In most cases, the data would not be encrypted or compressed as this would exacerbate the problem no. 1 above

The alternative which is, in my opinion, the only feasible method, is to store the data in a database. One of the most prevalent databases in use is MySQL. Data that is stored in a database can easily be indexed, managed and stored efficiently. Besides that, most databases also provide a suite of accompanying utilities that allow the database administrator to maintain the database – for example, backup and restore, etc.

Websites scripted using PHP are very well suited for the MySQL database as PHP has a custom and integrated MySQL module that communicates very efficiently with MySQL. PHP can also communicate with MySQL through the standard ODBC as MySQL is ODBC-compliant, However, this will not be as efficient as using the custom MySQL module for PHP.

The rest of this article is a tutorial on how to use PHP to:

  1. Connect to a MySQL database
  2. Execute standard SQL statements against the MySQL database

Starting a Session with MySQL

Before the PHP script can communicate with the database to query, insert or update the database, the PHP script will first need to connect to the MySQL server and specify which database in the MySQL server to operate on.

The mysql_connect() and mysql_select_db() functions are provided for this purpose. In order to connect to the MySQL server, the server name/address; a username; and a valid password is required. Once a connection is successful, the database needs to be specified.

The following 2 code excerpts illustrate how to perform the server connection and database selection:

@mysql_connect("[servername]", "[username]", "[password]") or die("Cannot connect to DB!");

@mysql_select_db("[databasename]") or die("Cannot select DB!");

The @ operator is used to suppress any error messages that mysql_connect() and mysql_select_db() functions may produce if an error occurred. The die() function is used to end the script execution and display a custom error message.

Executing SQL Statements against a MySQL database

Once the connection and database selection is successfully performed, the PHP script can now proceed to operate on the database using standard SQL statements. The mysql_query() function is used for executing standard SQL statements against the database. In the following example, the PHP script queries a table called tbl_login in the previously selected database to determine if a username/password pair provided by the user is valid.

Assumption:

The tbl_login table has 3 columns named login, password, last_logged_in. The last_logged_in column stores the time that the user last logged into the system.

// The $username and $passwd variable should rightly be set by the login form
// through the POST method. For the purpose of this example, we’re manually coding it.
$username = “john”;
$passwd = “mypassword”;

// We generate a SELECT SQL statement for execution.
$sql="SELECT * FROM tbl_login WHERE login = '".$username."' AND password = '".$passwd."'";

// Execute the SQL statement against the currently selected database.
// The results will be stored in the $r variable.
$r = mysql_query($sql);

// After the mysql_query() command executes, the $r variable is examined to
// determine of the mysql_query() was successfully executed.
if(!$r) {
    $err=mysql_error();
    print $err;
    exit();
}

// If everything went well, check if the query returned a result – i.e. if the username/password
// pair was found in the database. The mysql_affected_rows() function is used for this purpose.
// mysql_affected_rows() will return the number of rows in the database table that was affected
// by the last query
if(mysql_affected_rows()==0){
    print "Username/password pair is invalid. Please try again.";
}
else {

// If successful, read out the last logged in time into a $last variable for display to the user
    $row=mysql_fetch_array($r);
    $last=$row["last_logged_in"];
    print “Login successful. You last logged in at ”.$last.”.”;

}

The above example demonstrated how a SELECT SQL statement is executed against the selected database. The same method is used to execute other SQL statements (e.g. UPDATE, INSERT, DELETE, etc.) against the database using the mysql_query() and mysql_affected_rows() functions.

About The Author

This PHP scripting article is written by John L. John L is the Webmaster of The Ultimate BMW Blog! (http://www.bimmercenter.com).

The Ultimate BMW Blog!

daboss@bimmercenter.com

There are many different traffic analysis tools, ranging from simple counters to complete traffic analyzers. Although there are some free ones, most of them come with a price tag. Why not do it yourself? With PHP, you can easily create a log file within minutes. In this article I will show you how!

Getting the information

The most important part is getting the information from your visitor. Thankfully, this is extremely easy to do in PHP (or any other scripting language for that matter). PHP has a special global variable called $_SERVER which contains several environment variables, including information about your visitor. To get all the information you want, simply use the following code:

// Getting the information
$ipaddress = $_SERVER['REMOTE_ADDR'];
$page = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}";
$page .= iif(!empty($_SERVER['QUERY_STRING']), "?{$_SERVER['QUERY_STRING']}", "");
$referrer = $_SERVER['HTTP_REFERER'];
$datetime = mktime();
$useragent = $_SERVER['HTTP_USER_AGENT'];
$remotehost = @getHostByAddr($ipaddress);

As you can see the majority of information comes from the $_SERVER variable. The mktime() (http://nl2.php.net/mktime) and getHostByAddr() (http://nl2.php.net/manual/en/function.gethostbyaddr.php) functions are used to get additional information about the visitor.

Note: I used a function in the above example called iif(). You can get this function at http://www.phpit.net/code/iif-function.

Logging the information

Now that you have all the information you need, it must be written to a log file so you can later look at it, and create useful graphs and charts. To do this you need a few simple PHP function, like fopen (http://www.php.net/fopen) and fwrite (http://www.php.net/fwrite).

The below code will first create a complete line out of all the information. Then it will open the log file in “Append” mode, and if it doesn’t exist yet, create it.

If no errors have occurred, it will write the new logline to the log file, at the bottom, and finally close the log file again.

// Create log line
$logline = $ipaddress . '|' . $referrer . '|' . $datetime . '|' . $useragent . '|' . $remotehost . '|' . $page . "\n";

// Write to log file:
$logfile = '/some/path/to/your/logfile.txt';

// Open the log file in "Append" mode
if (!$handle = fopen($logfile, 'a+')) {
	die("Failed to open log file");
}

// Write $logline to our logfile.
if (fwrite($handle, $logline) === FALSE) {
	die("Failed to write to log file");
}

fclose($handle);

Now you’ve got a fully function logging module. To start tracking visitors on your website simply include the logging module into your pages with the include() function (http://www.php.net/include):

include ('log.php');

Okay, now I want to view my log file

After a while you’ll probably want to view your log file. You can easily do so by simply using a standard text editor (like Notepad on Windows) to open the log file, but this is far from desired, because it’s in a hard-to-read format.

Let’s use PHP to generate useful overviews for is. The first thing that needs to be done is get the contents from the log file in a variable, like so:

// Open log file
$logfile = "/some/path/to/your/logfile.txt";

if (file_exists($logfile)) {

	$handle = fopen($logfile, "r");
	$log = fread($handle, filesize($logfile));
	fclose($handle);
} else {
	die ("The log file doesn't exist!");
}

Now that the log file is in a variable, it’s best if each logline is in a separate variable. We can do this using the explode() function (http://www.php.net/explode), like so:

// Seperate each logline
$log = explode("\n", trim($log));

After that it may be useful to get each part of each logline in a separate variable. This can be done by looping through each logline, and using explode again:

// Seperate each part in each logline
for ($i = 0; $i < count($log); $i++) {
	$log[$i] = trim($log[$i]);
	$log[$i] = explode('|', $log[$i]);
}

Now the complete log file has been parsed, and we’re ready to start generating some interesting stuff.

The first thing that is very easy to do is getting the number of pageviews. Simply use count() (http://www.phpit.net/count) on the $log array, and there you have it;

echo count($log) . " people have visited this website.";

You can also generate a complete overview of your log file, using a simple foreach loop and tables. For example:

// Show a table of the logfile
echo '<table>';
echo '<th>IP Address</th>';
echo '<th>Referrer</th>';
echo '<th>Date</th>';
echo '<th>Useragent</th>';
echo '<th>Remote Host</th>';

foreach ($log as $logline) {
	echo '<tr>';

	echo '<td>' . $logline['0'] . '</td>';
	echo '<td>' . urldecode($logline['1']) . '</td>';
	echo '<td>' . date('d/m/Y', $logline['2']) . '</td>';
	echo '<td>' . $logline['3'] . '</td>';
	echo '<td>' . $logline['4'] . '</td>';

	echo '</tr>';

}

echo '</table>';

You can also use custom functions to filter out search engines and crawlers. Or create graphs using PHP/SWF Charts (http://www.maani.us/charts/index.php). The possibilities are endless, and you can do all kinds of things!

In Conclusion…

In this article I have shown you have to create a logging module for your own PHP website, using nothing more than PHP and its built-in functions. To view the log file you need to parse it using PHP, and then display it in whatever way you like. It is up to you to create a kick-ass traffic analyzer.

If you still prefer to use a pre-built traffic analyzer, have a look at http://www.hotscripts.com.

About The Author

Dennis Pallett is a young tech writer, with much experience in ASP, PHP and other web technologies. He enjoys writing, and has written several articles and tutorials. To find more of his work, look at his websites at http://www.phpit.net, http://www.aspit.net and http://www.ezfaqs.com.

Introduction

PHP can be used for a lot of different things, and is one of the most powerful scripting languages available on the web. Not to mention it’s extremely cheap and widely used. However, one thing that PHP is lacking, and in fact most scripting languages are, is a way to update pages in real-time, without having to reload a page or submit a form.

The internet wasn’t made for this. The web browser closes the connection with the web server as soon as it has received all the data. This means that after this no more data can be exchanged. What if you want to do an update though? If you’re building a PHP application (e.g. a high-quality content management system), then it’d be ideal if it worked almost like a native Windows/Linux application.

But that requires real-time updates. Something that isn’t possible, or so you would think. A good example of an application that works in (almost) real-time is Google’s GMail (http://gmail.google.com). Everything is JavaScript powered, and it’s very powerful and dynamic. In fact, this is one of the biggest selling-points of GMail. What if you could have this in your own PHP websites as well? Guess what, I’m going to show you in this article.

How does it work?

If you want to execute a PHP script, you need to reload a page, submit a form, or something similar. Basically, a new connection to the server needs to be opened, and this means that the browser goes to a new page, losing the previous page. For a long while now, web developers have been using tricks to get around this, like using a 1×1 iframe, where a new PHP page is loaded, but this is far from ideal.

Now, there is a new way of executing a PHP script without having to reload the page. The basis behind this new way is a JavaScript component called the XML HTTP Request Object. See http://jibbering.com/2002/4/httprequest.html for more information about the component. It is supported in all major browsers (Internet Explorer 5.5+, Safari, Mozilla/Firefox and Opera 7.6+).

With this object and some custom JavaScript functions, you can create some rather impressive PHP applications. Let’s look at a first example, which dynamically updates the date/time.

Example 1

First, copy the code below and save it in a file called ’script.js’:

var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  xmlhttp = new XMLHttpRequest();
}

function loadFragmentInToElement(fragment_url, element_id) {
    var element = document.getElementById(element_id);
    element.innerHTML = '<em>Loading ...</em>';
    xmlhttp.open("GET", fragment_url);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            element.innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.send(null);
}

Then copy the code below, and paste it in a file called ’server1.php’:

<?php
echo date("l dS of F Y h:i:s A");
?>

And finally, copy the code below, and paste it in a file called ‘client1.php’. Please note though that you need to edit the line that says ‘http://www.yourdomain.com/server1.php’ to the correct location of server1.php on your server.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN">
<html>
<head>
<title>Example 1</title>
<script src="script.js" type="text/javascript"></script>

<script type="text/javascript">
	function updatedate() {
		loadFragmentInToElement('http://www.yourdomain.com/server1.php', 'currentdate');
	}

</script>
</head>

<body>
	The current date is	<span id="currentdate"><?php echo date("l dS of F Y h:i:s A"); ?></span>.<br /><br />

	<input type="button" value="Update date" OnClick="updatedate();" />
</body>

</html>

Now go to http://www.yourdomain.com/client1.php and click on the button that says ‘Update date’. The date will update, without the page having to be reloaded. This is done with the XML HTTP Request object. This example can also be viewed online at http://www.phpit.net/demo/php%20on%20the%20fly/client1.php.

Example 2

Let’s try a more advanced example. In the following example, the visitor can enter two numbers, and they are added up by PHP (and not by JavaScript). This shows the true power of PHP and the XML HTTP Request Object.

This example uses the same script.js as in the first example, so you don’t need to create this again. First, copy the code below and paste it in a file called ’server2.php’:

<?php

// Get numbers
$num1 = intval($_GET['num1']);
$num2 = intval($_GET['num2']);

// Return answer
echo ($num1 + $num2);

?>

And then, copy the code below, and paste it in a file called ‘client2.php’. Please note though that you need to edit the line that says ‘http://www.yourdomain.com/server2.php’ to the correct location of server2.php on your server.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN">
<html>
<head>
<title>Example 2</title>
<script src="script.js" type="text/javascript"></script>

<script type="text/javascript">
	function calc() {
		num1 = document.getElementById ('num1').value;
		num2 = document.getElementById ('num2').value;

		var element = document.getElementById('answer');
		xmlhttp.open("GET", 'http://www.yourdomain.com/server2.php?num1=' + num1 + '&num2=' + num2);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				element.value = xmlhttp.responseText;
			}
		}
	    xmlhttp.send(null);
	}
</script>
</head>

<body>
	Use the below form to add up two numbers. The answer is calculated by a PHP script, and <em>not</em> with JavaScript. What's the advantage to this? You can execute server-side scripts (PHP) without having to refresh the page.<br /><br />

	<input type="text" id="num1" size="3" /> + <input type="text" id="num2" size="3" /> = <input type="text" id="answer" size="5" />

	<input type="button" value="Calculate!" OnClick="calc();" />
</body>

</html>

When you run this example, you can add up two numbers, using PHP and no reloading at all! If you can’t get this example to work, then have a look on http://www.phpit.net/demo/php%20on%20the%20fly/client3.php to see the example online.

Any Disadvantages…?

There are only two real disadvantages to this system. First of all, anyone who has JavaScript turned off, or their browser doesn’t support the XML HTTP Request Object will not be able to run it. This means you will have to make sure that there is a non-JavaScript version, or make sure all your visitors have JavaScript enabled (e.g. an Intranet application, where you can require JS).

Another disadvantage is the fact that it breaks bookmarks. People won’t be able to bookmark your pages, if there is any dynamic content in there. But if you’re creating a PHP application (and not a PHP website), then bookmarks are probably not very useful anyway.

Conclusion

As I’ve shown you, using two very simple examples, it is entirely possible to execute PHP scripts, without having to refresh the page. I suggest you read more about the XML HTTP Request Object (http://jibbering.com/2002/4/httprequest.html) and its capabilities.

The things you can do are limitless. For example, you could create an extremely neat paging system, that doesn’t require reloading at all. Or you could create a GUI for your PHP application, which behaves exactly like Windows XP. Just think about it!

Be aware though that JavaScript must be enabled for this to work. Without JavaScript this will be completely useless. So make sure your visitors support JavaScript, or create a non-JavaScript version as well.

About The Author

Dennis Pallett is a young tech writer, with much experience in ASP, PHP and other web technologies. He enjoys writing, and has written several articles and tutorials. To find more of his work, look at his websites at http://www.phpit.net, http://www.aspit.net and http://www.ezfaqs.com

dennispallett@gmail.com

Introduction

Cookies have long been used in PHP scripts, and are a very useful function. But what exactly are cookies? Maybe you have used then, but you still don’t know exactly what they are. Or you are completely new to cookies? It doesn’t matter, because in this tutorial I will show you exactly what cookies are, and what they are used for.

Cookies in a nutshell

Cookies are small pieces of information that is stored on the computer of your visitors. Each browser handles it differently, but most simply store the information in a small text file. Internet Explorer has a special folder, which can be found in your C:\Windows or C:\Windows\System32 folder. You can delete all your cookies, by going to the Options and ‘Clearing Cookies’ or deleting them by hand. I don’t recommend this though.

Almost every website uses cookies. If you go to Amazon.com, you will get several cookies. The same goes for CNN.com. Even Google uses cookies! They are extremely useful for (temporarily) storing information. For example, if you have a login system for your visitors, you could save their userid and password (very heavily encrypted!) so they are automatically logged in the next time they visit your website.

Or you could remember their last visit, and highlight everything that is new. And that’s just the beginning.

Using Cookies

Using cookies in PHP is extremely easy. In fact, there is nothing to it, because of PHP’s inbuilt setcookie() function (http://php.net/setcookie). Have a look at the documentation, and then try the following example:

<?php

// Set a cookie
// Cookie name: name
// Cookie value: Dennis Pallett
// Cookie expire: in 24 hours

setcookie ('name', 'Dennis Pallett', time() + (60*60*24));
?>

If you run the code above, then a cookie will be set. That’s all. The cookie name and value are pretty obvious. The cookie expire is when the cookie expires, or goes away. Simply use the time() function (http://php.net/time) and add the number of seconds you want to have the cookie available to it. In the example I added 60*60*24=86400 seconds, or 24 hours.

If you have looked at the documentation, you probably noticed there are additional arguments. As the documentation says, the path is to limit a cookie to a specific path on your web server. This is often used when you run multiple instances of the same script in separate directories. You can safely omit this argument when it doesn’t matter if the cookie is available site-wide.

There is also the domain argument. This can be used to limit the cookie to a specific sub-domain, e.g. test.example.com. You can also safely ignore this argument, or set it to .example.com (note the beginning period, this is essential!).

Finally, there is also the secure argument. This argument is only used for cookies that are sent over a secure HTTPS connection (SSL). Just ignore this argument, unless you’re working with a secure connection.

One thing that should be mentioned is that cookies must be set, before you display any HTML/text. It’s probably best if you turn on output buffering by putting ob_start() (http://php.net/ob_start) at the top of your page.

Now that you have set a cookie, you probably want to retrieve the value as well. After all, that is the whole point of using cookies. Thankfully, as PHP is ever so easy, you can retrieve the same way as you retrieve a GET value. See the following example to retrieve the value of the previous example:

<?php
echo 'Your name is ' . $_COOKIE['name'];
?>

This should print “Your name is Dennis Pallett”. There’s nothing more to it. It’s just that easy!

Finally, one thing you probably want to do as well is remove cookies. This is as easy as setting them. Simply change the value of the cookie to FALSE, and change the expire date to -3000 seconds. See the following example:

<?php
setcookie ('name', FALSE, time()-1000);
?>

Checking if cookies are enabled

Before you start using cookies, you must make sure your visitor has cookies enabled. This can be done with a simply PHP checking script. Unfortunately, the PHP page needs to reload to check for cookies. But this can be done very transparently, and your visitor should hardly notice anything.

The following example will first set a test cookie, then reload the page, and finally check whether cookies are enabled.

<?php
error_reporting (E_ALL ^ E_WARNING ^ E_NOTICE);

// Check if cookie has been set or not
if ($_GET['set'] != 'yes') {
	// Set cookie
	setcookie ('test', 'test', time() + 60);

	// Reload page
	header ("Location: checkcookies.php?set=yes");
} else {
	// Check if cookie exists
	if (!empty($_COOKIE['test'])) {
		echo "Cookies are enabled on your browser";
	} else {
		echo "Cookies are <b>NOT</b> enabled on your browser";
	}
}
?>

Run the code above, and see what the output is. Check if cookies are enabled in your browser. If they’re not enabled, then you can enable them by going to your browser’s options. Unfortunately, this is different from each browser, so I can’t give you exact instructions. But Google can.

Storing Arrays

One feature of cookies that is often missed in articles is the ability to story arrays. Cookies can be used to store multi-dimensional arrays, which can be extremely useful to store data.

Consider the following code;

<?php
setcookie ("name[first]", "Dennis", time() + (60*60*24));
setcookie ("name[last]", "Pallett", time() + (60*60*24));
?>

You can then display these two cookies using the following code:

<?php
echo "First Name: " . $_COOKIE['name']['first'];
echo "<br />Last Name: " . $_COOKIE['name']['last'];
?>

The cookie ‘name’ is an array, and has multiple values. You can even go deeper and have multi-dimensional arrays, e.g. $_COOKIE['name']['test']['something']['value']. You could store whole arrays of data in cookies. But beware that you don’t store too much data, there are certain size limits to cookies.

In Conclusion…

Cookies are really versatile, and can be used for a lot of different purposes. Many websites use cookies, and cookies can really make your website more personalized. Using cookies in PHP isn’t hard at all, and you should be able to use them without any difficulty.

Before actively using cookies in your website, you must check whether the visitor has enabled them in their browser. If they don’t have cookies enabled, you must either redirect to a non-cookies version of your website, or you can make sure your website also works without cookies.

You can download a sample script at http://www.phpit.net/demo/php%20and%20cookies/logger.zip, where cookies are used in a (somewhat) practical way. In this example, there is a logging module, called log.php and a display module, called history.php. Basically, you include the log.php in other PHP pages, and then you can view history.php to lookup all the pages you have viewed and how often. The example uses arrays, and stores them in cookies.

The examples in this article can be downloaded at http://www.phpit.net/demo/php%20and%20cookies/examples.zip.

If you have a really unique practical way of using cookies, please let me know at dennis [AT] nocertainty [DOT] com. I’d really like to hear about interesting ways of using cookies.

About The Author

Dennis Pallett is a young tech writer, with much experience in ASP, PHP and other web technologies. He enjoys writing, and has written several articles and tutorials. To find more of his work, look at his websites at http://www.phpit.net, http://www.aspit.net and http://www.ezfaqs.com

Custom Hooks is another powerful and most demanding feature provided by TierDeveloper. Custom Hooks work like database triggers. It could be your own business logic that you can activate before or after performing some database action(s). PreHooks and PostHooks are two ways, provided by TierDeveloper, through which you can embed your own logic in the generated code. Pre hook methods are called before the database access is performed whereas post hook methods are called after the database operations are performed.

Custom hooks can be specified wherever database access is performed. It includes standard operations, query methods, bulk operations and custom operations. User can generate skeleton code for custom hooks of the selected methods or he/she can use his/her own hooks class.

For your convenience and better understanding I have listed sample code here which shows how TierDeveloper embed custom hooks in the generated code. It is pretty self-explanatory.

public void UpdateCustomerInfo(Customers objInfo)
{
try
{
... ... .... .......
... ... .... .......

CustomersHooks hooks = new CustomersHooks();
status = hooks.PreUpdateCustomerInfo((System.Data.SqlClient.SqlConnection)getConnection(), objInfo);

if (status != CustomersHooks.SUCCESS_CONTINUE)
{
SetStatus(status == CustomersHooks.FAIL_NONCONTINUE ? EStatus.eFail : EStatus.eSuccess);
ReleaseCommand();
return;
}

AddCmdParameter("@CompanyName", TDevFramework.EDataType.eVarchar, objInfo.CompanyName, TDevFramework.EParamDirection.eInput, objInfo.IsNull("CompanyName"));
... ... .... .......
... ... .... .......
... ... .... .......

ExecuteNonQuery();

status = hooks.PostUpdateCustomerInfo((System.Data.SqlClient.SqlConnection)getConnection(), objInfo);

if (status != CustomersHooks.SUCCESS_CONTINUE)
{
... ... .... .......
... ... .... .......
return;
}

SetStatus(EStatus.eSuccess);
ReleaseCommand();
}
catch (Exception e)
{
... ... .... .......
... ... .... .......
throw e;
}
}

public class CustomersHooks
{
public const int SUCCESS_CONTINUE = 0;
public const int SUCCESS_NONCONTINUE = 1;
public const int FAIL_NONCONTINUE = 2;

public int PreUpdateCustomerInfo( System.Data.SqlClient.SqlConnection Conn, Customers objInfo)
{
//.. .. .. . .. ..
// . .. .. .. .. Put your own code here
return SUCCESS_CONTINUE;
}

public int PostUpdateCustomerInfo( System.Data.SqlClient.SqlConnection Conn, Customers objInfo)
{
	// .. .. .. .. . .. .. ..
	//	.. ..	 .. .. put your own code here.
return SUCCESS_CONTINUE;
}
}

About The Author

Ann Morris – I work in a software development Organization and interested in writing technical articles.
ann@alachisoft.com

This article is written by daBoss. daBoss is the Webmaster of Designer Banners. daBoss can be contacted at sales (at) designerbanners (dot) com.

Developing a Login System with PHP and MySQL

Most interactive websites nowadays would require a user to log in into the website’s system in order to provide a customized experience for the user. Once the user has logged in, the website will be able to provide a presentation that is tailored to the user’s preferences.

A basic login system typically contains 3 components:

  1. The component that allows a user to register his preferred login id and password
  2. The component that allows the system to verify and authenticate the user when he subsequently logs in
  3. The component that sends the user’s password to his registered email address if the user forgets his password

Such a system can be easily created using PHP and MySQL.

Component 1 – Registration

Component 1 is typically implemented using a simple HTML form that contains 3 fields and 2 buttons:

  1. A preferred login id field
  2. A preferred password field
  3. A valid email address field
  4. A Submit button
  5. A Reset button

Assume that such a form is coded into a file named register.html. The following HTML code excerpt is a typical example. When the user has filled in all the fields, the register.php page is called when the user clicks on the Submit button.

[form name="register" method="post" action="register.php"]
   [input name="login id" type="text" value="loginid" size="20"/][br]
   [input name="password" type="text" value="password" size="20"/][br]
   [input name="email" type="text" value="email" size="50"/][br]
   [input type="submit" name="submit" value="submit"/]
   [input type="reset" name="reset" value="reset"/]
[/form]

The following code excerpt can be used as part of register.php to process the registration. It connects to the MySQL database and inserts a line of data into the table used to store the registration information.

@mysql_connect("localhost", "mysql_login", "mysql_pwd") or die("Cannot connect to DB!");
@mysql_select_db("tbl_login") or die("Cannot select DB!");
$sql="INSERT INTO login_tbl (loginid, password and email) VALUES (".$loginid.”,”.$password.”,”.$email.”)”;
$r = mysql_query($sql);
if(!$r) {
   $err=mysql_error();
   print $err;
   exit();
}

The code excerpt assumes that the MySQL table that is used to store the registration data is named tbl_login and contains 3 fields – the loginid, password and email fields. The values of the $loginid, $password and $email variables are passed in from the form in register.html using the post method.

Component 2 – Verification and Authentication

A registered user will want to log into the system to access the functionality provided by the website. The user will have to provide his login id and password for the system to verify and authenticate.

This is typically done through a simple HTML form. This HTML form typically contains 2 fields and 2 buttons:

  1. A login id field
  2. A password field
  3. A Submit button
  4. A Reset button

Assume that such a form is coded into a file named authenticate.html. The following HTML code excerpt is a typical example. When the user has filled in all the fields, the authenticate.php page is called when the user clicks on the Submit button.

[form name="authenticate" method="post" action="authenticate.php"]
   [input name="login id" type="text" value="loginid" size="20"/][br]
   [input name="password" type="text" value="password" size="20"/][br]
   [input type="submit" name="submit" value="submit"/]
   [input type="reset" name="reset" value="reset"/]
[/form]

The following code excerpt can be used as part of authenticate.php to process the login request. It connects to the MySQL database and queries the table used to store the registration information.

@mysql_connect("localhost", "mysql_login", "mysql_pwd") or die("Cannot connect to DB!");
@mysql_select_db("tbl_login") or die("Cannot select DB!");
$sql="SELECT loginid FROM login_tbl WHERE loginid=’".$loginid.”’ and password=’”.$password.”’”;
$r = mysql_query($sql);
if(!$r) {
   $err=mysql_error();
   print $err;
   exit();
}
if(mysql_affected_rows()==0){
   print "no such login in the system. please try again.";
   exit();
}
else{
   print "successfully logged into system.";
   //proceed to perform website’s functionality – e.g. present information to the user
}

As in component 1, the code excerpt assumes that the MySQL table that is used to store the registration data is named tbl_login and contains 3 fields – the loginid, password and email fields. The values of the $loginid and $password variables are passed in from the form in authenticate.html using the post method.

Component 3 – Forgot Password

A registered user may forget his password to log into the website’s system. In this case, the user will need to supply his loginid for the system to retrieve his password and send the password to the user’s registered email address.

This is typically done through a simple HTML form. This HTML form typically contains 1 field and 2 buttons:

  • A login id field
  • A Submit button
  • A Reset button

    Assume that such a form is coded into a file named forgot.html. The following HTML code excerpt is a typical example. When the user has filled in all the fields, the forgot.php page is called when the user clicks on the Submit button.

    [form name="forgot" method="post" action="forgot.php"]
       [input name="login id" type="text" value="loginid" size="20"/][br]
       [input type="submit" name="submit" value="submit"/]
       [input type="reset" name="reset" value="reset"/]
    [/form]
    

    The following code excerpt can be used as part of forgot.php to process the login request. It connects to the MySQL database and queries the table used to store the registration information.

    @mysql_connect("localhost", "mysql_login", "mysql_pwd") or die("Cannot connect to DB!");
    @mysql_select_db("tbl_login") or die("Cannot select DB!");
    $sql="SELECT password, email FROM login_tbl WHERE loginid=’".$loginid.”’”;
    $r = mysql_query($sql);
    if(!$r) {
       $err=mysql_error();
       print $err;
       exit();
    }
    if(mysql_affected_rows()==0){
       print "no such login in the system. please try again.";
       exit();
    }
    else {
       $row=mysql_fetch_array($r);
       $password=$row["password"];
       $email=$row["email"];
    
       $subject="your password";
       $header="from:you@yourdomain.com";
       $content="your password is ".$password;
       mail($email, $subject, $row, $header);
    
       print "An email containing the password has been sent to you";
    }
    

    As in component 1, the code excerpt assumes that the MySQL table that is used to store the registration data is named tbl_login and contains 3 fields – the loginid, password and email fields. The value of the $loginid variable is passed from the form in forgot.html using the post method.

    Conclusion

    The above example is to illustrate how a very basic login system can be implemented. The example can be enhanced to include password encryption and additional functionality – e.g. to allow users to edit their login information.

    - Used with the author’s permission.

    About The Author

    Used with the author’s permission.

    This article is written by daBoss. daBoss is the Webmaster of Designer Banners. daBoss can be contacted at sales (at) designerbanners (dot) com.

    http://www.designerbanners.com/

  • As any Web Business startup knows, creating a Website is a bunch of work! You have to bother with content, layout, graphics and HTML links, just to name a few. What about your Meta Tags?

    Meta Tags are words that are placed in your web page to provide a title, description and keywords to the Search Engine spiders or crawlers. They are not visible to visitors. To see a sample, open any website and click “View” on the menubar, and choose “Source.” You’ll see the Meta Tags up top, within the Head section of the web page.

    Most Search Engines will rank your site on how well your Meta Tags provide a description of the content of your web pages. Google is the exception; it also take’s into account the number and quality of backward links to your website. Here lately, there’s been differing opinions on the relevancy of Google’s Page Rank system. Some experts don’t consider it accurate or necessary.

    Yet and still, there are many other Search Engines and a further study of Meta Tags is in order. We are going to base our Meta Tags revision on a tool known as a word Frequency Counter. It counts and separates the words in a web page or document, giving you an idea of what words are used most.

    Here are some Web based Frequency Counters:

    Each one of the Frequency Counters above has different uses and qualifications. The Writewords counter has two flavors: word and phrase count. The Web4Future counter is Web based or a standalone download.

    How to use them:

    Copy and paste the content of the web page in question and see what the top word frequencies are. You can eliminate most articles and modifiers and concentrate on pure words. As an example: If your web page is about red and blue widgets, the words “red/blue/widgets” should have the highest frequency.

    A Word of Caution About Writing Content:

    Use the Frequency Counters AFTER you write the web page content. Don’t allow word frequency to get in the way of your natural writing style. Do NOT attempt to hit a certain frequency percentage; you’ll be penalized by many Search Engines for too much keyword usage.

    In Closing

    Though the word Frequency Counters are good tools for a quick check, nothing compares to laser-focused writing for good Meta Tags information. Let your writing flow naturally and stay concentrated on your subject keywords. If you do that, you’ll find it easy to weave your keywords into your content and Meta Tags.

    by Francisco Aloy

    (C)2004 Francisco Aloy

    About The Author

    Francisco Aloy is the creator of The Newbie Business Guide.
    Constructive and clear information for your new Internet Business.
    To see more of Mr. Aloy’s articles, visit: http://www.newbie-business-guide.com

    « Previous PageNext Page »