February 7, 2012

The Toolbelt: Some of my most-used code snippets for PHP, MySQL, HTML and CSS.

By Daniel

I’ve meant to work on this for quite a while. These are some of my most used code snippets to shorten a process, handy workarounds, pieces of code I need all the time or other such things.

HTML: The Meta Redirect

Use case: You need to redirect someone to another page, and don’t want to bother notifying them.

Code: [code][/code]

Advantages: Silent, works cross-platform, timer can be set (in whole seconds) by adjusting the 0 in content, will work in the body even though it’s a meta tag.
Disadvantages: Breaks back buttons.

PHP/MySQL: Quickly process and sanitize form data.

Use case: You’ve just accepted a form and want to easily work with the data, and escape the data to prevent SQL injection attacks.

Code: [code]foreach($_POST as $key=>$value) { $$key=addslashes($value); }[/code]

Advantages: Saves a lot of repetitive entering of $_POST[‘element’]. Instead you just use $element. Also escapes the data early on so we don’t forget further along in the code.
Disadvantages: You create a lot of variables instead of one array. Your array isn’t actually destroyed, just copied. The idea is that the backend is working primarily with this POST data so making a lot of variables isn’t an unwanted thing.

PHP/MySQL: Save an if statement on every mysql_error() check.

Use case: You need to use mysql_error() function to handle errors in your SQL statement.

Old code: [code]$result = mysql_query($query);
if(!$result) { die(mysql_error()); }[/code]

New code: [code]$result = mysql_query($query) or die(mysql_error());[/code]

Advantages: Reduces risk of typos breaking your page, cleaner.
Disadvantages: No known disadvantages.

PHP/MySQL: One standardized method of DB querying.

Use case: You want to get in the habit of one naming scheme for your MySQL queries, and don’t want to go the OOP route.

Code: [code]function doQuery($query) {
$result = mysql_query($query) or die(mysql_error());
return $result; }

$q_descriptivename = “SELECT * FROM table WHERE 1”;
$descriptivename = doQuery($q_descriptivename);[/code]

Note: No advantage or disadvantage here, I just thought I’d share the way I do my queries. I usually have a functions.php file with things like doQuery, doConnect, and so forth. I then make the file a require_once() in my header.php. There are more efficient ways to do it via object-oriented code, but there are certainly less efficient ways too.

PHP: Regex out non-numerals from a phone number, then put them back for display purposes.

Use case: You have a form input for a phone number, and want to be guaranteed it works in your database. If you’re trying to optimize and want to use a CHAR(10), or just want a unified dataset to work against. Really it’s common sense to have all your data be uniformly stored here.

[code]$phone=preg_replace(“/[^0-9.]/”, “”, $phone); // strip non-numerals
if (strlen($phone) == 7) { $phone = “505”.$phone; } // if the user was too lazy to add their area code, add the expected one. Handle this how you like.

$disp_phone = preg_replace(“/^(\d{3})(\d{3})(\d{4})$/”, “($1) $2-$3”, $phone); //present it in the standard (123) 456-7890 format.[/code]

Advantages: Regular expressions take a lot of possible entries and catch them all. One-line solutions are always preferable to a switch or some such.
Disadvantages: The code above is a very crude handling of too few numbers, but the regex can be tweaked to accommodate that or you can do it via Javascript.

CSS: 3-column div-based website with a “sticky footer”

Use case: You find tables too outdated and confining, and would rather use divs and CSS.

Code: 3colstickyfooter.css

Note: The “sticky footer”, where the footer is on the bottom of the page even when the rest of the content doesn’t reach that far, is a surprisingly tricky behavior to get right. You can see the result here. Notice how the footer stays stuck to the bottom of the window as you resize it.

PHP/CSS/HTML: Blind-friendly, captcha-free, spam-fighting input field.

Use case: I had a client that was opposed to captchas, yet one of his forms was constantly hammered by spammers and filled his mailbox. Thus I designed a hidden text input field that spambots fill out, blind users are audibly instructed to leave empty, and sighted users never see.

Code: [code]HTML:

If you’re human leave this blank.

CSS: tr .robotic { display: none; }

PHP: if(strlen($_POST[‘url’]) > 0) { die(); }[/code]

Advantages: The home-brewed nature of this solution has resulted in a 100% decrease in spam getting through. We thwart the spammer by knowing they don’t respect CSS; they just look at a page as raw HTML and fill in data wherever possible. Naming the field “url” guarantees the spammer is going to put a link in it, and then the PHP sees there is data in the field and silently rejects it. Just use a different input name for your real URL field. This also eliminates false positives and frustrating re-validation attempts by end-users that can’t read the captcha.
Disadvantages: No known disadvantages.