Skip to content

Instantly share code, notes, and snippets.

@ryanellis
Last active July 18, 2023 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanellis/0ee6152494117457d6739d96a6932476 to your computer and use it in GitHub Desktop.
Save ryanellis/0ee6152494117457d6739d96a6932476 to your computer and use it in GitHub Desktop.
Old-school PHP debugger
<?php
/**
* Print out argument to log file - note, arrays, objects are printed via var_dump()
* Useful for debugging an application where the logging implementation isn't great
*/
function d($msg) {
$bt = debug_backtrace();
$caller_bt = $bt[0];
$filename = basename($caller_bt['file']);
$loc = "[$filename:$caller_bt[line]] ";
if (!is_string($msg)) {
$val = ini_set('html_errors', 0);
ob_start();
var_dump($msg);
$msg = ob_get_clean();
ini_set('html_errors', $val);
}
file_put_contents('/tmp/php-debug.log', $loc.$msg.PHP_EOL, FILE_APPEND);
}
/**
* Print out a backtrace
*/
function dtrace($msg) {
ob_start();
$old = ini_set('html_errors', 'off');
if (!function_exists('xdebug_print_function_stack')) {
echo $msg, PHP_EOL;
debug_print_backtrace();
}
else {
xdebug_print_function_stack($msg);
}
ini_set('html_errors', $old);
$out = ob_get_clean();
d($out);
}
/**
* Return a debug backtrace (safe to use on production)
*/
function dpbtrace() {
ob_start();
debug_print_backtrace();
$out = ob_get_clean();
return $out;
}
// Example usage:
// Drupal: add to /sites/default/settings.php
// Moodle: add to /config.php
// make sure to create the target log file `/tmp/php-debug.log`, you might need to chown this to be the `www-data` user/group to allow PHP to write to it
// simply call d(); for anything you want to view in the logs - e.g. d($my_variable); or d('useful degug comment');
d('--------------- new bootstrap initiated -------------------');
/*
// e.g.
touch /tmp/php-debug.log
chmod 775 /tmp/php-debug.log
chown www-data:www-data /tmp/php-debug.log
wget https://gist.githubusercontent.com/ryanellis/0ee6152494117457d6739d96a6932476/raw -O debug.php
php -r 'require_once("debug.php"); d(array("some", "stuff", "here", 1, 2, 3));'
cat /tmp/php-debug.log
[debug.php:56] --------------- new bootstrap initiated -------------------
[Command line code:1] array(6) {
[0]=>
string(4) "some"
[1]=>
string(5) "stuff"
[2]=>
string(4) "here"
[3]=>
int(1)
[4]=>
int(2)
[5]=>
int(3)
}
*/
/*
Useful command to append directly to Moodle config.php file
touch /tmp/php-debug.log
chmod 775 /tmp/php-debug.log
chown www-data:www-data /tmp/php-debug.log
wget https://gist.githubusercontent.com/ryanellis/0ee6152494117457d6739d96a6932476/raw -O - | tail -n +2 >> config.php
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment