Clarence Eldefors blog Mostly about the web and technology


PHP, small tips and tricks #1

Purpose of this post series is to give a few tips on how to improve your code. It's not the most important practices, but some common things to see done in a less than elegant way.

For adding days or weeks to a timestamp, don't count your seconds.


$nextDay = $todayTimestamp + 86400;


$nextDay = strtotime('+1 day', $todayTimestamp);

The first one will fail when you move into or out of daylight savings time. An extra pro is that the second example is a hell lot more readable. Especially if you add something like 2 weeks and 4 days ('+2 weeks 4 days')

Validate and sanitize with filter_var()

Don't use regexp to filter/match an email or an URL. There's already builtin filters in PHP for it:


$email = filter_var('', FILTER_VALIDATE_EMAIL);

See documentation on:
Available filters

Tagged as: , No Comments