Execute a background task in PHP

There are a ton of ways of running a task in the background (like a daemon, etc) from PHP but this must surely be the slickest –

sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile)

This will execute $cmd, writing it’s output to $outputfile, and saving it’s pid in $pidfile. The last two can be /dev/null of course.

Getting input from stdin during composer installation

By adding a “post-install-cmd” option to your scripts section of composer.json you can setup commands to run after “composer install”, however, these won’t wait for input if you want to collect something (like a username) in a php script.

You can have the exact same effect though by calling the function like so —

"post-install-cmd": [

Where Class is your classname and function is a static function that uses stdin to get information.

Show signs on PHP numbers

PHP automatically shows a negative sign for negative numbers but getting it to show a positive sign (e.g. when you are showing growth/loss) can be a mess of if statements. Rather, use this —

sprintf("%+d", $number);

You’ll then get +1234 instead of just 1234.

Ultimate do “not cache this page” for PHP

Below is the ultimate set of headers to send from PHP to ensure a page is not cached —

header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");