JSON is the future

Web2.0 is taking the internet by storm. The next generation of websites will all be developed using Web 2.0 technologies, ie AJAX. Though I still think that AJAX is bad for search engine optimization, I am fully supportive of using AJAX to create web applications. JSON is another buzz word that comes into the picture when we talk about AJAX.

I was inspired to write an introductory article on JSON after a long talk with my colleague designer. I have been using AJAX and JSON for a while now and haven’t really wrote anything on it… thought that it is a good idea to share the basics of JSON with everyone – JSON for beginners

Another Email Scam

I always receive emails saying that you will get paid for doing surveys. When you mouse over the link, you will see the link is actually pointing towards another ip address, possibly someone else computer. The sender will usually be tactical, ie you will normally be asked some simple questions and then when you reach the last step, YOUR CREDIT CARD DETAILS!

All the steps, prompts and graphics are believable and if you are not aware, you will enter the credit card details in the last step. What happens after that? bye bye, your credit card details are now stolen.

This type of scam can be spotted easily by moving or clicking on the links in the mail. There are however, more intelligent ones such as customizing the mouseover display and redirecting you to a similar website after you arrived at the scam website. Some scam sites uses sub-domains so that it is more believable, such as ebay.xxxx.com… so that you might think that the site is actually an ebay site!

Another good way to find out if the email is a scam is that you visit the site ONLY after a few days you receive the mail. If it is a scam, the site will most likely be gone. Scammers are intelligent, they will not put a scam site for long period of time so that the police have a chance to catch them.

I receive this one today:

————- BEGINNING OF SCAM ———————- 

Dear Valued Customer,

CONGRATULATIONS !!!

You have been chosen by the Washington Mutual online department to take part in our quick and easy 5 question survey. In return we will credit $20 to your account – Just for your time!

Helping us better understand how our customers feel benefits everyone. With the information collected we can decide to direct a number of changes to improve and expand our online service.
The information you provide us is all non-sensitive and anonymous – No part of it is handed down to any third party groups.
It will be stored in our secure database for maximum of 3 days while we process the results of this nationwide survey.

We kindly ask you to spare two minutes of your time in taking part with this unique offer!

To Continue click on the link below:

http://www.wamu.com/secure/online.wamu.com/IdentityManagement/index.html?Washington-Mutual-survey

Many Thanks and Kind Regards – Washington Mutual Bank Customer Department

———————— END OF SCAM ——————

Yes, one more thing…. to make sure you don’t fall into the hands of scammers, don’t click on the links, instead copy the whole url and paste it in the browser. That way, you make sure that you are visiting the actually website and not the scammer’s website.

Be smart. Don’t believe in any scheme or surveys asking you to give your bank or credit card details. If you do wish to pay, always check that the page is secure, ie starts with a https:// instead of a http.

So Beware friends! If you are retired and are looking for home jobs, get rich schemes…etc, this little piece of IT knowledge might save you from giving away your hard earned money.

Automated Link Exchange

From time to time, I get email saying something like this:

“Dear Webmaster,

My name is Jason and I have just gone through your site, and visited many pages. I have noticed that you have good content on the site. It would be better if we link to each other as reciprocal link place an important role in a search engine ranking algorithm.

I have already placed a link to your site on the following webpage: …..

Kindly link to us with ….”

Isn’t automated email great? The webmaster usually list your site in a low traffic and pr page and expect you to list their site in your high traffic and pr page!

Available For Freelance Work

I am re-entering uni soon for post graduate course in web development. If you need extra hands in PHP, MYSQL, XML, Web Services, SEO…etc, I might be able to help. just email me and we can chat about it. We can meet up if you are in melbourne.

online framing software

Yourframer is a picture framing application that enables the user to upload their own images and frame it online. The user can match the matboards colors and frames till they are satisfied before purchasing the materials.

The entire application is developed using Object Oriented PHP, PEAR, AJAX and XML.

http://clubframeco.com/smartFramer.html

Its amazing how prototype is integrated so tightly into the application. I’ll be extending the application to include image downloading from other internet sites… hopefully one day, many websites can send files over to the program in just a click. Any comments welcomed.

Working With Fractions In PHP

Displaying Fractions In HTML

There are a few ways to display fractions in the web. The most common way is just to add a slash between 2 numbers, like so “1/2”. There are also special HTML characters that we can make fractions look more professional. Eg. to display 1/2, we can use the HTML code ½. However, not many fractions are supported by HTML. So, you may be in trouble if you want to display 2/9 in HTML.

A better way to display a fraction is probably to use the superscript and subscript tags. The HTML will be 2/9. We can also use a “special slash” ⁄ between 2 numbers instead of a normal slash ( / ) to make the fraction look better. The fraction will now look like this: 2⁄9. Still not satisfied? With CSS, we can push the limit further.

If we define a css like this:

.fracNum, .fracDen {

font-size: 70%; } .fracNum { vertical-align: 0.5em; } .fracDen { vertical-align: -0.5em; }

and when implemented with the superscript and subscript tags :

2⁄9

The fraction will now be displayed like this: 3⁄16

* The fractions might not be displayed correctly because of the online editor.

Converting Decimals To Fraction – A Real Example

I wrote a program that let people frame their pictures online. When I was halfway through, I was told that the program should support imperial measurements (inches). The problem with working in inches is that very few people would say my picture is 6.34 inch width by 9.82 inch height; Most people would say 6 and 3/8 inch by 9 and 3/8 height for example.

The biggest problem now is that the framing engine calculates everything in mm. Instead of rewritting the whole engine, I figured out that what I need is just an interface to convert mm to inches. So, if I pass 300mm into a function, it should return me 11 and 3/4 as the answer. Dividing 300mm by 1 inch (25.4mm) will leave me with a long decimal. It would be silly to try and display a fraction for a decimal like 0.1111. The function should be intelligent enough to round off the decimal to something that can be easily displayed as a fraction. For example, if I round off 0.1111 to 0.125, I can display the fraction as 1/8 instead of 1111/100000. Time is running short and I need a simple and sweet solution.

Implementation

I would like to go through snipplets of code with explaination first before revealing everything. Feel free to jump to the end of the page and copy the whole function if you just want to implement it in your website. The code is written in PHP.

Part 1: Extracting the decimal in inches.

define(INCH_TO_MM, 25.4);

// 1 inch equals to 25.4mm

$inch = $mm / INCH_TO_MM;

$pWhole = explode(‘.’,$inch); $pWhole = $pWhole[0];

$pDecimal = $val-$pWhole;

The measurement in mm is first converted to inches(with decimal). The decimal is then isolated from the whole number and stored in a var call $pDecimal. Now, I need to store a list of all possible fractions with their mm equivalent in an array. I use intervals of 1/8 for the sake of simplicity.

Part 2: Rounding off to the closest inch interval.

$fractionOption = array();

$fractionOption[‘0/8’] = 0;

$fractionOption[‘1/8’] = 0.125;

$fractionOption[‘1/4’] = 0.25;

$fractionOption[‘3/8’] = 0.375;

$fractionOption[‘1/2’] = 0.5;

$fractionOption[‘5/8’] = 0.625;

$fractionOption[‘3/4’] = 0.75;

$fractionOption[‘7/8’] = 0.875;

$fractionOption[‘8/8’] = 1;

foreach ($fractionOption as $k => $v) {

// Converted $pDecimal back to mm to perform calculation

$tmpV[$k] = abs($pDecimal – $v);

}

asort($tmpV,SORT_NUMERIC);

list($inch, $mm) = each($tmpV);

This is the most important step in the whole conversion process. The foreach loop creates a new array called $tmpV which stores the inch fraction as the key and the inch difference as the value. We will now sort $tmpV with the minimum ‘mm’ value at the top and the maximum ‘mm’ value at the bottom using the ‘asort’ function. We are extracting the first entry in the array because it stores the minimum ‘mm’ difference. As you can see, what we are trying to do here is to round $pDecimal off to the closest decimal value in the $fractionOption array (ie, 0.125, 0.25, 0.375..etc).

I can now safely extract the first key-value pair in $tmpV using the ‘list’ function. The $inch var stores the inch representation that we want.

Part 3: Cleaning Up

$inch = ($inch == ‘0/8’) ? ”: $inch; // round off to nearest whole number if 8/8 if ($inch == ‘8/8’) { $inch = ”;

$pWhole++; }

We do not want to display the fraction if it is ‘0/8’ or ‘8/8’ because it is pretty much meaningless. However, if the fraction is ‘8/8’, we have to increase the whole number by 1.

Part 4: Adding some CSS

if ($inch != ”) {

$tFrac = explode(‘/’,$inch);

$fraction = “$tFrac[0]⁄$tFrac[1]”; } else {

$fraction = ”; } return “$pWhole $fraction”;

Remember that we eliminated any fractions that are ‘0/8’ or ‘8/8’? So we only need to process any fraction that falls within the range of ‘1/8’ to ‘7/8’. By splitting the fractions into numerators and denominators, we can now apply our CSS technique mentioned above.

The Whole Thing

As promised, the full code is displayed below:

function mmToInch ($val) {

$fractionOption = array();

$fractionOption[‘0/8’] = 0;

$fractionOption[‘1/8’] = 0.125;

$fractionOption[‘1/4’] = 0.25;

$fractionOption[‘3/8’] = 0.375;

$fractionOption[‘1/2’] = 0.5;

$fractionOption[‘5/8’] = 0.625;

$fractionOption[‘3/4’] = 0.75;

$fractionOption[‘7/8’] = 0.875;

$fractionOption[‘8/8’] = 1;

define(INCH_TO_MM, 25.4);

$val = $val/INCH_TO_MM;

$pWhole = explode(‘.’,$val);

$pWhole = $pWhole[0];

$pDecimal = $val-$pWhole;

foreach ($fractionOption as $k => $v) {

$tmpV[$k] = abs($pDecimal – $v);

}

asort($tmpV,SORT_NUMERIC);

list($inch, $mm) = each($tmpV);

// nullify pWhole and pFraction

$pWhole = ($pWhole == 0) ? ”: $pWhole;

$inch = ($inch == ‘0/8’) ? ”: $inch;

// round off to nearest whole number if 8/8

if ($inch == ‘8/8’) {

$inch = ”;

$pWhole++;

}

// strip inch and return fraction formatted in css

if ($inch != ”) {

$tFrac = explode(‘/’,$inch);

$fraction = “$tFrac[0]⁄$tFrac[1]”;

}

else {

$fraction = ”;

}

return $pWhole.’ ‘.$fraction; }

// testing echo “67.885 mm is equivalent to “.mmToInch(66.885).” inches”;

?>

The sourcecode can be dowloaded here

Form Checking – Verifying Name Using PHP Ereg

One important use of Regular Expressions (Regex) is to verify fields submitted via a form. In this article, we attempt to write an expression that is able to verify the user’s first name, middle name, last name or just names in general.

The expression should allow names such as “Mary”, “Mr. James Smith” and “Mrs O’Shea” for example. So the challenge here is to allow spaces, periods and single quotation marks in the name field and reject any other characters.

Technique

We try to identify and detect all illegal characters in the name field. I came up with the following list:

Punctuations: ~`!@#$%^&*()=+{}|\:;<>“/?,

Numerics: 0-9

Noticed that I left out the empty space ( ), period (.) and single quotation mark (‘) because we are allowing these 3 characters to pass the verification. In other words, the verification will fail if the name field contains any of the punctuations or numerics above.

The Regex

Now, the hardcore part. The regex pattern I came up with is as follows:

([[:digit:]]|[~`!@#$%^&*\(\)_=\+{}\|\\:;<>“/?,]|\[|\]|-)+

Let me briefly explain what this pattern means. The expression can be represented by:(expression1 | expression2 | expression3 | expression4 | expression5)

What we are trying to do here is to match the name field to the patterns in expression 1, 2, 3, 4 or 5. If you look at the regex closely, you will see that expression1 is actually [[:digit:]].

Expression2 is:

[~`!@#$%^&*\(\)_=\+{}\|\\:;<>“/?,]

Noticed that I added a backslash (\) before each of the 5 characters “()+|\”. By backslashing these characters, I am telling the function to treat the characters as it is and not as special built-in characters. For example, the brackets “()” actually means grouping in regex but if I backslash it, ie “\(\)”, it simply means that I want to match “(” and “)”.

Expression3 is “\[“, expression 4 is “\]” and expression 5 is “-“. We left out the 3 characters “[]-” in expression2 just to avoid confusion because we already used “[]” as the outer brackets. As for “-“, we left it out because it is normally used as a range within the brackets “[]”, like so [A-Z].

Implementation

To implement it in PHP, we write the code as follows:

$pattern = ‘([[:digit:]]|[~`!@#$%^&*\(\)_=\+{}\|\\:;<>“/?,]|\[|\]|-)+’;
$name = stripslashes({$_POST[‘name_field’]});
if (ereg($pattern,{$_POST[‘name_field’]})) {
echo “write your error message”;
}

We stripslashed the name field just in case your have magic quotes turned on. If magic quotes is turned on, the single quotation mark will be passed as \’ instead just ‘. The ereg function will look for digits and illegal punctuations in the $_POST name field. If an error is found, we can do something such as alerting the user of the error.

Conclusion

Hopefully, this article can give you some insight into regex and save you some time when verifying name fields. You can modify the regex to have stricter rules for example, you may not want the name field to start with a space or a period. That’s all for now. Cheers.

 

Introduction to Regular Expressions In PHP

In Linux and Unix, the syntax that is commonly used by many applications for specifying text patterns is known as regular expressions or in short form – regex. Regex is a very powerful technique to describe patterns and many programs use them to describe sequences of characters to be matched. Search programs such as ‘grep’ rely heavily on regex. Basically regex forms the core in the linux world. Many scripting languages such as perl, ruby, php…etc has build in regex functions as well. So you can see, learning regular expression is important because they are used alot in many places and probably more so in the future. 

Regex can be scary at first but if you can get the basics, it is really not too hard to understand. In this article, we are going to look at how regex comes into the picture when writing php applications.

In simple terms, a regular expression is a sequence of literal characters, wildcards, modifiers and anchors.

Literal Characters

Literal characters are letters, digits and special characters that match only themselves. Examples are abc, 123, ~@ and so on (some characters are reserved though).

– An inclusion range [m-n] matches one of any character included in the range from m to n. Example ‘[a-z]’ will match any alpha character that falls within the a to z range.
– An exclusion range [^m-n] matches one of any character not included in the range from m to n. Example ‘[^0-9]’ will match any non-digit character.
– A period “.” matches any character. It is also known as the wildcard. Example ‘a.c’ will match ‘aec’, ‘acc’, ‘a@a’ and so on.
– The escape character ” enable interpretation of special characters. Example ‘a.c’ will match ‘ac’ only. Remember that ‘.’ is a reserved character to represent a wildcard? Therefore to match a period, ie ‘.’, we need to escape it like so ‘.’
– The expression [:alnum:] will match all alpha-numeric characters. It is a shortcut to [A-Za-z0-9]. As you can see, it is not really a shortcut. The expression [:alnum:] might be easier to remember for some people.
– The expression [:alpha:] will match all alpha characters. It is a shortcut to [A-Za-z].
– The expression [:blank:] will match a space or tab.
– The expression [:digit:] will match a numeric digit. It is a shortcut to [0-9].
– The expression [:lower:] will match all lowercase letters. It is a shortcut to [a-z].
– The expression [:upper:] will match all uppercase letters. It is a shortcut to [A-Z].
– The expression [:punct:] will match all printable characters, excluding spaces and alphanumerics.
– The expression [:space:] will match a whitespace character.

Modifiers

A modifier alters the meaning of the immediately preceding pattern character.

– An asterisk (‘*’) matches 0 or more of the preceding term. Example ‘a*’ will match ”, ‘a’, ‘aa’, ‘aaaaa’ and so on (Note the use of ”. It simply means that the expression matches nothing as well).
– A question mark (‘?’) matches 0 or 1 of the preceding term. Example ‘a?’ will match ” and ‘a’ only.
– A plus sign (‘+’) matches 1 or more of the preceding term. Example ‘a+’ will match ‘a’, ‘aaaaaaa’ and so on. It will not match ”.
– {m,n} matches between m and n occurences of the preceding term. Example ‘a{1,3}’ will match ‘a’, ‘aa’ and ‘aaa’ only.
– {n} matches exactly n occurences of the preceding term. Example ‘a{2}’ will match ‘aa’ only.

Anchors

Anchors establish the context for the pattern such as “the beginning of a word” or “end of word”.

– The pike ‘^’ marks the beginning of a line. Example ‘^http’ will match any new line that starts with ‘http’.
– The dollar sign ‘$’ marks the end of a line. Example ‘after$’ will match any line that ends with ‘after’. (Variables in php starts with $. Try not to confuse with it).

Grouping

Grouping ‘( )’ allows modifiers to apply to groups of regex specifiers instead of only the immediately proceding specifier. Example ‘( aa | bb )’ will match either ‘aa’ or ‘bb’

Enough of boring stuff, it is time to put what the theory of regex into good use.

PHP Implementation

There are 2 main variants of regex, Perl-compatible regex (PCRE) and POSIX-Extended. PHP offers quite alot of functions to implement these 2 types of regex. In PHP, the most commonly used PCRE function is ‘preg_match’ and in POSIX-extended regex, ‘ereg’. Both syntax are slightly different but equally powerful. The preference to use ‘preg_match’ or ‘ereg’ is entirely up to individual although Zend suggested that preg_match is slightly faster. I prefer to use ‘eregi’ simply because of my background in linux administration.

Example 1: Matching United States 5 or 9 digit zip codes

Zip codes in USA have the following format ##### or #####-#### where # is a digit. If you want to verify the zip code submitted say from an online form, you will need to use regex somewhere in your script to verify it. The matching POSIX-extended regex pattern will be:

[[:digit:]]{5}(-[[:digit:]]{4})?

Confused? Wait, let me explain why. This regex is split up into 2 parts: [[:digit:]]{5} and (-[[:digit:]]{4})?.

First Part: ‘[[:digit:]]’ means the digit range and {5} means that the digit must occur 5 times.

Second Part: The bracket ‘( )’ groups the ‘-[[:digit:]]{4}’ together and the ‘?’ means the expression ‘(-[[:digit:]]{4})’ can either occur 0 or 1 time.

To implement the regex in PHP, we use the following code:

$zipCodes = ‘xxxxx-xxxx’;
$pattern = ‘[[:digit:]]{5}(-[[:digit:]]{4})?’;
if (ereg($pattern,$zipCodes)) {
echo “matched found “;
}
else {
echo “match not found”;
}

Example 2: Matching Dates

Say we want to verify the dates entered by the user. If we only accept dates like “YYYY-MM-DD” or “YYYY-M-D”, the regex pattern will be

[0-9]{4}(-[0-9]{1,2})+

The ‘+’ behind the term (-[0-9]{1,2}) means that the term must occur at least once. Note that I can also rewrite the regex as:

[[:digit:]]{4}(-[[:digit:]]{1,2})+

or

[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}

As you can see, there can be many solutions to a problem…

Conclusion

Regex may be hard to digest at first but the logic is simple if you are able to practice more. Learning regex is as important as learning PHP. More examples can be seen at web-developer.sitecritic.net. Good luck.