24Oct/120
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.
DON'T:
$nextDay = $todayTimestamp + 86400;
DO:
$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:
Example:
$email = filter_var('bob@example.com', FILTER_VALIDATE_EMAIL);
See documentation on:
filter_var()
Available filters