Skip to content

Instantly share code, notes, and snippets.

@hattmarris
Last active November 10, 2015 20:30
Show Gist options
  • Save hattmarris/5ca7e835441b27b10011 to your computer and use it in GitHub Desktop.
Save hattmarris/5ca7e835441b27b10011 to your computer and use it in GitHub Desktop.
Command Line PHP
<?php
/**
* Run PHP in terminal / command line:
* $ php -a
*/
// Get input from stdin command line
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
// dump debug contents to a custom log file
file_put_contents('custom_file.log', $line . PHP_EOL, FILE_APPEND); // FILE_APPEND dont overwrite
// get contents of var_dump of an object printable for logging
class aClass {
public $a = true;
public $b = 'the string';
public function aMethod() {
echo 'Hello World';
}
}
$object = new aClass;
function varDumpLog($object) {
ob_start();
var_dump($object);
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
$c = varDumpLog($object);
echo $c . PHP_EOL;
/* displays:
object(aClass)#1 (2) {
["a"]=>
bool(true)
["b"]=>
string(10) "the string"
}
*/
/**
* Helper time difference logging function
*
* $start time from PHP microtime(true) // returns seconds as float
* $end time from PHP microttime(true)
*/
function logTimeDiff($start, $end) {
$seconds = $end - $start;
$milli = $seconds / 1000;
return $milli . 'ms, ' . $seconds . 'sec' . PHP_EOL;
}
// PHP mictrotime() If get_as_float is set to TRUE, then microtime() returns a float
// which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.
function testLogTimeDiff($microseconds) {
$a = microtime(true);
usleep($microseconds);
echo logTimeDiff($a, microtime(true));
}
testLogTimeDiff(2000000); // wait for 2 seconds
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment