- История PHP и смежных проектов
- Migrating from PHP 7.0.x to PHP 7.1.x
- Migrating from PHP 5.6.x to PHP 7.0.x
- Migrating from PHP 5.5.x to PHP 5.6.x
- Migrating from PHP 5.4.x to PHP 5.5.x
- Переход с PHP 5.3.x на PHP 5.4.x
- Переход c PHP 5.2.x на PHP 5.3.x
- Переход с PHP 5.1.x на PHP 5.2.x
- Переход с PHP 5.0.x на PHP 5.1.x
- Переход с PHP 4 на PHP 5.0.x
- Classes and Objects (PHP 4)
- Отладка в PHP
- Опции конфигурации
- Директивы php.ini
- Список/классификация расширений
- Список псевдонимов функций
- Список зарезервированных слов
- Список типов ресурсов
- Список доступных фильтров
- Список поддерживаемых транспортных протоколов
- Таблица сравнения типов в PHP
- Список меток (tokens) парсера
- Руководство по именованию
- Об этом руководстве
- Creative Commons Attribution 3.0
- Алфавитный список
- Список изменений
Коментарии
I still find that printing out variable values at problem points in the code is one of the easiest ways for me to debug. If you're interested in knowing the full contents of an object/array/scalar, then use
var_dump($var).
p_r() is a function for logging variable values.
In this example the function p_r() does only log when the URL parameter d=<nonzero> is set. Reset it by d=0.
When the parameter is a valid filename (relative to the script's path) it will be logged to that file rather than to the browser.
[code]
@session_start();
// debug
if (isset($_GET['d']))
{
$_SESSION['d'] = $_GET['d'];
}
if (@$_SESSION['d']) {
function p_r($exp)
{
$res = "";
$trace = debug_backtrace();
$level = 0;
$e = error_reporting(E_ALL&~E_NOTICE);
$file = strrpos($trace[$level]['file'], "/");
$file = substr($trace[$level]['file'],$file+1);
$line = date("H:i:s"). " " . $file . ' ' . $trace[$level]['line'] . ' ' . $trace[$level+1]['function'] . "()";
$e = error_reporting($e);
if (!is_string($exp)) $exp = var_export($exp,1);
if (substr($_SESSION["d"],-4)==".log") {
file_put_contents ($_SESSION["d"],$line . ": ". $exp . "\n", FILE_APPEND);
} else {
$res = $line . "\n<pre>".htmlentities($exp). "</pre>\n";
echo $res;
}
return $res;
}
// refresh to prevent timeout
$a = $_SESSION['d'];
$_SESSION['d'] = $a;
error_reporting (E_ALL);
} else {
function p_r() {}
} // end if debug
[/code]
I find it very useful to print out to the browsers console instead of just var_dumping:
function console_log( $data ){
echo '<script>';
echo 'console.log('. json_encode( $data ) .')';
echo '</script>';
}
Usage:
$myvar = array(1,2,3);
console_log( $myvar ); // [1,2,3]
I would like to add http://phpdebugbar.com/ which is also a handy tool for debugging/profiling data. and you could use it whenever framework you are using. :-)
Following example above using variable-lenght arguments to support similar Web API's console.log implementation
<?php
function console_log( ...$messages ){
$msgs = '';
foreach ($messages as $msg) {
$msgs .= json_encode($msg);
}
echo '<script>';
echo 'console.log('. json_encode($msgs) .')';
echo '</script>';
}
?>
None of the given examples here do fit my needs.
When I debug, I want to see clearly what's going on and where is the debug data. Also it has to accommodate with the current styles and not fall behind or get mixed with other text etc.
This snippet will give you real debug notices in a flashy table:
- complete backtrace of calls on the left with line numbers
- arguments content on the right, with the variable name and coloring per variable type
<?php
function wtf(){
error_reporting(E_ALL);
$args = func_get_args();
$backtrace = debug_backtrace();
$file = file($backtrace[0]['file']);
$src = $file[$backtrace[0]['line']-1]; // select debug($varname) line where it has been called
$pat = '#(.*)'.__FUNCTION__.' *?\( *?\$(.*) *?\)(.*)#i'; // search pattern for wtf(parameter)
$arguments = trim(preg_replace($pat, '$2', $src)); // extract arguments pattern
$args_arr = array_map('trim', explode(',', $arguments));
print '<style>
div.debug {visible; clear: both; display: table; width: 100%; font-family: Courier,monospace; border: medium solid red; background-color: yellow; border-spacing: 5px; z-index: 999;}
div.debug > div {display: unset; margin: 5px; border-spacing: 5px; padding: 5px;}
div.debug .cell {display: inline-flex; padding: 5px; white-space: pre-wrap;}
div.debug .left-cell {float: left; background-color: Violet;}
div.debug .array {color: RebeccaPurple; background-color: Violet;}
div.debug .object pre {color: DodgerBlue; background-color: PowderBlue;}
div.debug .variable pre {color: RebeccaPurple; background-color: LightGoldenRodYellow;}
div.debug pre {white-space: pre-wrap;}
</style>'.PHP_EOL;
print '<div class="debug">'.PHP_EOL;
foreach ($args as $key => $arg) {
print '<div><div class="left-cell cell"><b>';
array_walk(debug_backtrace(),create_function('$a,$b','print "{$a[\'function\']}()(".basename($a[\'file\']).":{$a[\'line\']})<br> ";'));
print '</b></div>'.PHP_EOL;
if (is_array($arg)) {
print '<div class="cell array"><b>'.$args_arr[$key].' = </b>';
print_r(htmlspecialchars(print_r($arg)), ENT_COMPAT, 'UTF-8');
print '</div>'.PHP_EOL;
} elseif (is_object($arg)) {
print '<div class="cell object"><pre><b>'.$args_arr[$key].' = </b>';
print_r(htmlspecialchars(print_r(var_dump($arg))), ENT_COMPAT, 'UTF-8');
print '</pre></div>'.PHP_EOL;
} else {
print '<div class="cell variable"><pre><b>'.$args_arr[$key].' = </b>>';
print_r(htmlspecialchars($arg, ENT_COMPAT, 'UTF-8').'<');
print '</pre></div>'.PHP_EOL;
}
print '</div>'.PHP_EOL;
}
print '</div>'.PHP_EOL;
}
?>
Usage: wtf($arg1, $arg2,..);
That's it!
I also use a method to print complete data from www.skydevelopers.net company:
function dd($data) {
echo '<pre>';
print_r($data);
exit;
}
well this is also very beneficial