McKremie
Tuesday June, 9th
Posted by Nathan

AJAX was, and remains, the hottest buzzword in web development. This will continue to hold true for the foreseeable future, and for good reason; sites which use it are pretty slick. Yet the acronym, which stands for Asynchronous JavaScript and XML, continues to be misused and misplaced. Have you made one of these all-too-common mistakes?

1) I Need an AJAX Guru to Code an AJAX Website

Any proficient JavaScript coder can use AJAX. The fact of the matter is, every function of an AJAX powered site is standard JavaScript. An AJAX site simply uses XmlHttpRequest() to send and receive server requests. In fact the acronym itself, while catchy, is an all-around misnomer. The techniques commonly thought of as AJAX require neither the returned data to be XML, nor the requests to be asynchronous (although they can be both).

2) AJAX is New

AJAX, the acronym, is new. The term was coined in 2005. The technology behind AJAX is not new. JavaScript has been part of the Internet since the 1990s. A method to request data through JavaScript has been in browsers as early as IE5.

3) AJAX Powered Websites are Fast

Properly implemented, AJAX can make site navigation much faster for the end-user. Having the browser refresh and render a page takes a lot of time. Preventing this, by requesting and updating only portions of the page, is very efficient. However, without a good implementation or proper infrastructure, AJAX can bring your server to a stand still with excess or unnecessary requests.

4) I need to add AJAX to my website to keep up with the times

Is this true? It depends entirely on your site. While sites from Google to Facebook use AJAX successfully, many others simply do not. If you decide that your site could benefit from AJAX, ideally a site with very dynamic content, design your implementation carefully. Keep in mind that your site must degrade properly if JavaScript isn’t available. Make sure key content remains linkable and accessible. Not only could you risk having frustrated users, you could give search bots nothing to see.

5) AJAX Will Replace Flash

While it’s true that Flash was once the buzzword that AJAX now is in web development circles, the idea that AJAX will replace completely flash is unfounded. While entirely flash based designs are becoming increasingly uncommon, flash still serves a purpose for many multimedia and graphical interface elements.

While AJAX has given many great possibilities in web development, consider the technology carefully before implementing it on your own site. Don’t break the likability, accessibility or navigation (back/forward buttons) of a site just to use AJAX. Use it where it is the most efficient way to make something work.

Friday May, 22nd
Posted by Nathan

An intro to CAPTCHAs

Captcha is an acronym for Completely Automated Public Turing test to tell Computers and Humans Apart. You’ll likely recognize them as Security Images, a series of random letters or numbers, which you have to enter when sending data on most websites. This verifies that you are a human, and not a robot entering data automatically, such as a spam bot.

Captchas aren’t perfect; a spammer can still solve a captcha manually, and software may be created to solve specific captchas to varying degrees of success, but they are still essential for modern websites. They help to dramatically reduce spam and false form entries. Fortunately, it’s relatively easy to make a unique captcha with PHP and GD.

Designing a Captcha

GD is a powerful graphics library for PHP. Good hosting providers will have this library installed by default. To start off we’ll want to create an image based on a background that provides some interference for optical character reading (OCR) software, but not enough to cause difficulty for humans. The following 4 backgrounds will be used in this example:

Secondly, a unique truetype font (TTF) should be chosen. Although this tutorial will use a simple sans-serif font, feel free to look for something more interesting.

Finally, a character set must be chosen. Some prefer a combination of letter and numbers, or each individually. Either way, characters that resemble others should be avoided.

Once you have these key elements chosen, you’ll want the script to generate and display a random string which will be saved in a session. The displayed string should be altered to make it more difficult for software to recognize the characters.

Putting it Together

With your captcha planned, it’s time to put it into code. The following will begin to create your image from a random PNG background, as well as setup variables such as the font and security string:

ob_start();
session_start();

$im = ImageCreateFromPNG(mt_rand(1, 4).”.png”);

$chars = array(’a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’,’i’,’j’,’k’,’m’,’n’,’p’,’q’,’r’,’t’,’u’,’v’,’w’,’x’,’y’,’z’,’2?,’3?,’4?,’6?,’7?,’8?,’9?);
$str1 = $chars[mt_rand(0, count($chars)-1)];
$str2 = $chars[mt_rand(0, count($chars)-1)];
$str3 = $chars[mt_rand(0, count($chars)-1)];
$str4 = $chars[mt_rand(0, count($chars)-1)];

$font = “font.ttf”;
$size = mt_rand(13, 16);

$_SESSION['captcha'] = $str1.$str2.$str3.$str4;

The code below is slightly more complicated, as it outputs the text at a random angle, and slightly different positions/colors. You’ll likely want to play with the output parameters.

$angle = mt_rand(-5, 5);
$color = ImageColorAllocate($im, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100));
$textsize = imagettfbbox($size, $angle, $font, $textstr);
$twidth = abs($textsize[2]-$textsize[0]);
$theight = abs($textsize[5]-$textsize[3]);
$x = mt_rand(5, 10);
$y = mt_rand(15,18);
ImageTTFText($im, $size, $angle, $x, $y, $color, $font, $str1);
ImageTTFText($im, $size, $angle, $x+mt_rand(20, 25), $y+mt_rand(1, 3), $color, $font, $str2);
ImageTTFText($im, $size, $angle, $x+mt_rand(45, 50), $y+mt_rand(1, 3), $color, $font, $str3);
ImageTTFText($im, $size, $angle, $x+mt_rand(65, 70), $y+mt_rand(1, 3), $color, $font, $str4);

Finally, we’ll have the following code output our finalized image.

header(”Content-Type: image/png”);
ImagePNG($im);
ob_end_flush();
imagedestroy($im);

Integrating The Final Product

The code above should output something like the following (refresh to see another):

The text in the captcha is stored in a PHP session. This can be accessed in your scripts using the global variable $_SESSION['captcha']. Be sure to call session_start(); at the start of your script first.

Further Considerations/References

To strengthen your captcha further, look into some of the many functions GD has: GD Reference. A great place to find many free fonts is UrbanFonts.com or DaFont.com

Feel free to use the code above as you see fit. It has been released as GPL v2 as part of an open source project that I worked on. The background images are also free to use, however I would recommend creating your own.

Monday May, 11th
Posted by Nathan

mod_rewrite is a powerful URL Rewriting Engine for the Apache web server. Although available in varying forms in other server software, this post will focus on the Apache rewriting engine.

What is URL Rewriting?

In short, mod_rewrite allows for a the server to respond in a specific way based on conditions met by the URL. This allows for many possibilities, including the creation of user friendly URL schemes for your dynamic scripts.

For example, if you have a PHP article script which requires an article id in the URL, this would typically be accomplished by:

http://example.com/news.php?id=2

However, mod_rewrite can turn that URL into the following:

http://example.com/news/2/news-article-title

The rewritten URL is much more meaningful to users and search engines. The URL is far more memorable without the php extension and id request. The article title provides search engines with more keywords, which can help with your search ranking. These benefits become even more apparent as more complicated URLs are rewritten into friendlier forms.

Getting Started

mod_rewrite is used by adding rules and conditions to a file named .htaccess in a site’s directory. The rewrite engine must first be turned on. Open or create a .htaccess file and add the following:

RewriteEngine on

A basic URL rewrite can be performed by adding a Rewrite Rule, formatted as follows:

RewriteRule pattern substitution [flags]

The pattern is a regular expression (regex), matched to the current URL. The substitution is the replacement or change made to the pattern matched URL. Flags are optional arguments which modify the way the rewrite engine acts.

To implement the rewrite example above, the following code is used:

RewriteEngine on
RewriteRule ^/news/([0-9]+)/(.+)(/)$ /news.php?id=$1 [L]

The pattern is started with ^, and ends with $. The brackets represent groups, the first matches any number of digits, the second matches any number of characters, followed by an optional trailing slash. The substitution tells the server to fetch news.php, with an id of the first group in the pattern, $1. The L flag tells the rewrite engine that this is the last rewrite to be performed.

Conditional Rewriting

To further expand control over the rewrite engine, Rewrite Conditions can be set. These allow for conditions to be matched before a Rewrite Rule is to be executed. The following syntax is used:

RewriteCond TestString CondPattern

The TestString can be one of a number of system variables, such as the current referrer or browser user agent. The CondPattern is again a regular expression, which will be matched against the TestString. A useful application to a rewrite condition is to check if files or images are being hotlinked.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?example.com/.*$ [NC]
RewriteRule ^\.(gif|jpg|png|bmp)$ http://example.com/donothotlink.jpg [R,L]

The conditions check if there is no referrer, or if it is from a different site. If one of those conditions are met, the rule checks if the file being accessed is an image. If so, the user is redirected (using the R flag) to an image explaining that the requested image was hotlinked.

Other Possibilities

Some common uses of mod_rewrite include; redirecting to another page based on browser user agent, moving a site to another domain, forcing the addition or removal of www. on your domain, etc.

Although mod_rewrite can be difficult to learn and master, the possibilities are endless.

Further Reading and References

Official Apache mod_rewrite Documentation
Added Bytes mod_rewrite Cheat Sheet