Protecting Email Addresses Using ASCII Codes
In the browser, you just see an email link; however, the underlying HTML markup is indecipherable: <a href="mailto: email@address.xy">Send mail</a> Protecting Email Addresses (protectMail.php)<?php function protectMail($s) { $result = ''; $s = 'mailto:' . $s; for ($i = 0; $i < strlen($s); $i++) { $result .= '&#' . ord(substr($s, $i, 1)) . ';'; } return $result; } echo '<a href="' . protectMail('email@address.xy') . '">Send mail</a>'; ?> However, take a look at Figure 1.3: The email address is decoded correctly by the web browser, as can be seen in the status bar. Figure 1.3. Machine beats man (when deciphering the email address).Some special characters are difficult to use in strings because they are hard to enter using a keyboard. However, they all have an ASCII value. PHP offers two functions to deal with this:
This can be used to protect email addresses, for instance. Because spammers are writing software to search for certain patterns (email adresses) on web pages, this might help keep spam low. The trick is to use HTML character codes for email addresses, making it much harder for spambots to find email data. The preceding code takes an email address (in the format email@address.xy) as a parameter and returns mailto:email@address.xybut converted into HTML entities. For instance, the m of mailto: has the ASCII code 109; therefore, $#109; stands for m. To do so, a for loop iterates through all characters in the string. To do so, the length of the string has to be determined, which can be done using strlen(). Then, a call to ord() calculates the ASCII code of each character, which is then used for the resulting HTML. Of course, this does not offer a bulletproof protection; you might consider using alternative ways to obscure the email address, including a syntax such as email at address dot xy. Printing Strings, Variables, and Expressions SimultaneouslyUsing double quotation marks, printing a mixture of strings and variables is easy to do. However, when you also want to use expressions such as function calls, the standard way is to use lots of string concatenations: echo 'The length of the string is ' . strlen($s) . '!'; This is obviously getting rather complex when several expressions are involved. A more convenient way is to use printf(). As parameters, you provide first a string with placeholders, and then the values for those placeholders. Table 1.1 shows which values are allowed for a placeholder.
The following shows how printf() makes the code a bit easier to read: <?php $a = 'PHP'; $b = 'php'; printf('strcmp(): %d<br />strcasecmp(): %d', strcmp($a, $b), strcasecmp($a, $b)); ?> PHP also supports several functions related to printf():
|