Guidelines

This site is for tech Q&A. Please keep your posts focused on the subject at hand.

Ask one question at a time. Don't conflate multiple problems into a single question.

Make sure to include all relevant information in your posts. Try to avoid linking to external sites.

Links to documentation are fine, but in addition you should also quote the relevant parts in your posts.

0 votes
709 views
709 views

I need to debug a webpage written in PHP, but I don't want to set up a debugger, remote debugging session and whatnot. How can I do that?

in Scripting
by (125)
3 19 33
edit history

Please log in or register to answer this question.

1 Answer

0 votes
 

Assuming you have shell access to the webserver (or at least some kind of file access) you can add a small output function at the top of the page (in the global scope):

<?php

function debug_out($msg) {
  $f = fopen('/tmp/debug.log', 'a+');
  if (!$f) {
    trigger_error('Cannot open debug log.', E_USER_ERROR);
    return;
  }
  fputs($f, "$msg\n");
  fclose($f);
}

// rest of the PHP page below this
...

Then sprinkle the code with debug_out() calls

...
debug_out($some_variable);
...

so you can see the value of $some_variable in the output file. Add some unique identifiers to avoid confusion about which statement created the output line:

...
debug_out("\$some_variable, line 42: $some_variable");
...

Use JSON for displaying complex data structures:

...
$json = json_encode($some_variable, JSON_PARTIAL_OUTPUT_ON_ERROR);
debug_out('$some_variable, line 42: ' . ($json ? $json : json_last_error_msg()));
...

or, probably better, use print_r():

...
debug_out('$some_variable, line 42: ' . print_r($some_variable, true));
...

Note that for the latter the second parameter must be set to true, otherwise the data will be printed (i.e. shown on the page) instead of being returned and logged.

If you have shell access, /tmp is a good location for a temporary debug log file, since the directory is usually world-writable. If you don't have shell access you need to find a location where the web server can create files that you then can download for inspection.


edited by
by (125)
3 19 33
edit history
...