Skip to content

Instantly share code, notes, and snippets.

@schuyberg
Last active September 27, 2017 23:54
Show Gist options
  • Save schuyberg/312f5e6b8373ad24a0d85a9581226213 to your computer and use it in GitHub Desktop.
Save schuyberg/312f5e6b8373ad24a0d85a9581226213 to your computer and use it in GitHub Desktop.
log to the JS console from PHP
// use this anywhere in your php app
function console_log() {
$messages = func_get_args();
if(!$GLOBALS['cLogs']){
$GLOBALS['cLogs'] = array();
}
$GLOBALS['cLogs'] = array_merge($GLOBALS['cLogs'], $messages);
}
// use this at the bottom of the global template (or wherever you can insert some js)
// probably worth adding a check for dev/prod env, ie. (strpos($env, 'dev') == -1)
function print_logs(){
if (!$GLOBALS['cLogs']) {
return false;
} else {
echo "<script>";
foreach($GLOBALS['cLogs'] as $k => $l) {
if (is_string($l)) {
echo "console.log('$l');";
} else {
echo "console.log(" . json_encode($l, JSON_PRETTY_PRINT) . ");";
}
}
echo "</script>";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment