PHP 스크립트를 어떻게 디버깅합니까? [닫은]
PHP 스크립트를 어떻게 디버깅 합니까?
오류보고 사용과 같은 기본 디버깅을 알고 있습니다. PHPEclipse 의 중단 점 디버깅 도 매우 유용합니다.
phpStorm 또는 다른 IDE에서 디버깅 하는 가장 빠르고 쉬운 방법은 무엇입니까?
언급 한 것과 같은 디버깅 기능이있는 Eclipse 환경을 설정하려면 Eclipse PDT 를 사용해보십시오 . 코드로 들어가는 기능은 이전의 var_dump 메소드를 디버깅하고 다양한 지점에서 인쇄하여 흐름이 잘못되는 위치를 확인하는 훨씬 좋은 방법입니다. 모든 사람은 비록 실패하고 내가 가진 모든 SSH 내가 여전히 정력 때 var_dump()
/ die()
코드가 남쪽 어디로 찾을 수 있습니다.
Firephp 애드온을 사용하여 자바 스크립트와 동일한 환경에서 PHP를 디버깅하기 위해 firebug를 사용할 수 있습니다.
또한 앞에서 언급 한 PHP 프로파일 링을 위해 Xdebug 를 사용 합니다.
이것은 내 작은 디버그 환경입니다.
error_reporting(-1);
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_BAIL, 0);
assert_options(ASSERT_QUIET_EVAL, 0);
assert_options(ASSERT_CALLBACK, 'assert_callcack');
set_error_handler('error_handler');
set_exception_handler('exception_handler');
register_shutdown_function('shutdown_handler');
function assert_callcack($file, $line, $message) {
throw new Customizable_Exception($message, null, $file, $line);
}
function error_handler($errno, $error, $file, $line, $vars) {
if ($errno === 0 || ($errno & error_reporting()) === 0) {
return;
}
throw new Customizable_Exception($error, $errno, $file, $line);
}
function exception_handler(Exception $e) {
// Do what ever!
echo '<pre>', print_r($e, true), '</pre>';
exit;
}
function shutdown_handler() {
try {
if (null !== $error = error_get_last()) {
throw new Customizable_Exception($error['message'], $error['type'], $error['file'], $error['line']);
}
} catch (Exception $e) {
exception_handler($e);
}
}
class Customizable_Exception extends Exception {
public function __construct($message = null, $code = null, $file = null, $line = null) {
if ($code === null) {
parent::__construct($message);
} else {
parent::__construct($message, $code);
}
if ($file !== null) {
$this->file = $file;
}
if ($line !== null) {
$this->line = $line;
}
}
}
Xdebug 및 강력한 버그 사냥을위한 메모장 ++ 용 DBGp 플러그인, 가벼운 것들을위한 FirePHP. 빠르고 더러운? 아무것도 dBug를 이길 수 없습니다 .
XDebug 는 개발에 필수적입니다. 다른 확장 프로그램보다 먼저 설치합니다. 모든 오류에 대한 스택 추적을 제공하며 프로파일 링을 쉽게 활성화 할 수 있습니다.
데이터 구조를 간단히 살펴 보려면 사용하십시오 var_dump()
. print_r()
당신은 그것을 둘러싸고 있어야하고 <pre>
한 번에 하나의 var 만 인쇄 하기 때문에 사용하지 마십시오 .
<?php var_dump(__FILE__, __LINE__, $_REQUEST); ?>
실제 디버깅 환경에서 내가 찾은 최고의 것은 Komodo IDE 이지만 $$입니다.
PhpEd는 정말 좋습니다. 기능을 시작 / 종료 / 종료 할 수 있습니다. 임시 코드를 실행하고 변수를 검사하고 변수를 변경할 수 있습니다. 놀랍습니다.
1) print_r ()을 사용합니다. TextMate에는 다음과 같이 확장되는 'pre'에 대한 스 니펫이 있습니다.
echo "<pre>";
print_r();
echo "</pre>";
2) Xdebug를 사용하지만 Mac에서 GUI가 제대로 작동하지 못했습니다. 최소한 읽기 가능한 버전의 스택 추적을 인쇄합니다.
내가 사용했습니다 젠드 스튜디오 (5.5) 과 함께, 젠드 플랫폼 . 적절한 디버깅, 중단 점 / 코드 스테핑 등을 제공하지만 가격은 비쌉니다.
정직하게, 변수를 인쇄하기 위해 print와 print_r ()의 조합. 많은 사람들이 다른 고급 방법을 선호하지만 이것이 가장 사용하기 쉬운 방법이라는 것을 알고 있습니다.
Uni에서 마이크로 프로세서 프로그래밍을하고이 기능을 사용할 수 없을 때까지이 점을 완전히 이해하지 못했다고 말할 것입니다.
Derick Rethans의 Xdebug 는 매우 좋습니다. 얼마 전에 사용했는데 설치가 쉽지 않은 것으로 나타났습니다. 완료되면, 당신은 그것없이 어떻게 관리했는지 이해할 수 없습니다 :-)
Zend Developer Zone 에 대한 좋은 기사 (Linux에 설치하는 것이 더 쉬워 보이지는 않습니다)와 Firefox 플러그인 도 있습니다.
XDebug와 함께 Netbeans를 사용합니다. 구성 방법에 대한 문서는 웹 사이트에서 확인하십시오. http://php.netbeans.org/
XDebug 및 Easy XDebug FireFox 애드온 과 함께 Netbeans를 사용 합니다.
Netbeans에서 XDebug가 실행되는 일반적인 방법은 URL을 통해 dbug 세션을 등록하는 것이므로 MVC 프로젝트를 디버깅 할 때 애드온이 필수적입니다. FireFox에 애드온을 설치하면 Netbeans 프로젝트 속성-> 구성 실행-> 고급을 설정하고 "웹 브라우저를 열지 마십시오"를 선택하십시오. 이제 평소와 같이 중단 점을 설정하고 Ctrl-F5를 사용하여 디버깅 세션을 시작할 수 있습니다 . FireFox를 열고 오른쪽 하단 모서리에있는 애드온 아이콘을 마우스 오른쪽 단추로 클릭하여 중단 점 모니터링을 시작하십시오. 코드가 중단 점에 도달하면 중지되고 변수 상태 및 콜 스택을 검사 할 수 있습니다.
출력 버퍼링은 출력을 엉망으로 만들고 싶지 않은 경우 매우 유용합니다. 나는 1 개의 라이너로 이것을 수행한다.
ob_start();var_dump(); user_error(ob_get_contents()); ob_get_clean();
PhpEdit에는 디버거가 내장되어 있지만 일반적으로 echo ()를 사용합니다. 그리고 print_r (); 구식 방법 !!
print_r / echo를 사용하여 IDE의 (PhpEd) 디버깅 기능을 사용하는 데 너무 많은 시간이 걸리는 매우 거친 문제의 경우. 필자가 사용한 다른 IDE와 달리 PhpEd는 설정이 거의 필요하지 않습니다. 내가 직면 한 문제에 대해 그것을 사용하지 않는 유일한 이유는 고통스럽게 느리기 때문입니다. 속도가 PhpEd 또는 PHP 디버거와 관련이 있는지 확실하지 않습니다. PhpEd는 무료가 아니지만 어쨌든 오픈 소스 디버거 중 하나 (예 : XDebug)를 사용한다고 생각합니다. PhpEd의 장점은 과거에는 실제로 매우 지루한 설정이 필요 없다는 것입니다.
수동 디버깅은 일반적으로 빨리 나를 위해입니다 - var_dump()
그리고 debug_print_backtrace()
당신이 당신의 논리를 무장하는 데 필요한 모든 도구이다.
글쎄, 어느 정도는 남쪽으로가는 곳에 달려 있습니다. 이것이 가장 먼저 분리하려고 한 다음 필요에 따라 echo / print_r ()을 사용합니다.
NB : print_r ()에 두 번째 인수로 true를 전달할 수 있으며 출력하는 대신 출력을 반환한다는 것을 알고 있습니까? 예 :
echo "<pre>".print_r($var, true)."</pre>";
Rails가 불가능할 때 종종 CakePHP를 사용합니다. 오류를 디버깅하려면 일반적으로 error.log
tmp 폴더에서를 찾아 터미널에서 명령으로 꼬리를 붙입니다 ...
tail -f app/tmp/logs/error.log
그것은 당신이 무슨 일이 일어나고 있는지에 대한 케이크에서 대화 상자를 실행하게합니다. 사용할 수있는 코드 중간에 무언가를 출력하고 싶다면 매우 편리합니다.
$this->log('xxxx');
이것은 일반적으로 무슨 일이 일어나고 있는지에 대한 좋은 아이디어를 줄 수 있습니다.
print_r (debug_backtrace ());
또는 그런 것 :-)
Komodo IDE는 remore 디버깅에도 xdebug와 잘 작동합니다. 최소한의 구성이 필요합니다. Komodo가 로컬에서 사용하여 중단 점에서 코드를 단계별로 실행할 수있는 PHP 버전 만 있으면됩니다. komodo 프로젝트로 스크립트를 가져온 경우 마우스 클릭으로 중단 점을 설정하여 Java 프로그램 디버깅을 위해 이클립스에서 스크립트를 설정하는 방법을 설정할 수 있습니다. 원격 디버깅은 MAC 또는 Linux 데스크톱에있는 경우 구성하기가 쉬운 로컬 디버깅 설정보다 올바르게 작동하기 위해 분명히 까다 롭습니다 (작업 공간에서 PHP 스크립트로 원격 URL을 매핑해야 할 수도 있음). .
Nusphere는 PHP Nusphere를 위한 좋은 디버거입니다
코딩 할 때 수많은 시간을 절약 할 수있는 많은 PHP 디버깅 기술이 있습니다. 효과적이지만 기본적인 디버깅 기술은 단순히 오류보고를 설정하는 것입니다. 약간 더 발전된 또 다른 기법은 print 문을 사용하는 것인데, 실제로는 화면에 실제로 발생하는 것을 표시하여 더 어려운 버그를 찾아 낼 수 있습니다. PHPeclipse는 일반적인 구문 오류를 강조 표시하고 디버거와 함께 사용하여 중단 점을 설정할 수있는 Eclipse 플러그인입니다.
display_errors = Off
error_reporting = E_ALL
display_errors = On
또한 사용
error_log();
console_log();
프로덕션 환경에서는 error_log ()를 사용하여 관련 데이터를 서버의 오류 로그에 기록합니다.
내장 디버거와 함께 일식에 zend studio를 사용합니다. xdebug를 사용하는 이클립스 pdt로 디버깅하는 것에 비해 여전히 느립니다. 그들이 이러한 문제를 해결하기를 바라며, 최근 릴리즈에서는 속도가 향상되었지만 여전히 스테핑은 2-3 초가 걸립니다. zend firefox 툴바는 실제로 작업을 쉽게 해줍니다 (다음 페이지, 현재 페이지 등). 또한 코드를 벤치마킹하고 파이 차트, 실행 시간 등을 제공하는 프로파일 러를 제공합니다.
대부분의 버그는 var_dump
주요 변수 중 일부를 간단히 사용하여 쉽게 찾을 수 있지만, 어떤 종류의 응용 프로그램을 개발 하느냐에 따라 달라집니다.
보다 복잡한 알고리즘의 경우 단계 / 중단 점 / 감시 기능이 매우 유용합니다 (필요하지 않은 경우).
PHP DBG
대화식 Stepthrough PHP 디버거는 SAPI 모듈로 구현되어 코드의 기능이나 성능에 영향을주지 않고 환경을 완벽하게 제어 할 수 있습니다. PHP 5.4+를위한 가볍고 강력하며 사용하기 쉬운 디버깅 플랫폼을 목표로하며 PHP 5.6과 함께 기본 제공됩니다.
특징은 다음과 같습니다.
- 단계별 디버깅
- 유연한 중단 점 (클래스 메소드, 함수, 파일 : 라인, 주소, Opcode)
- 내장 eval ()을 사용하여 PHP에 쉽게 액세스
- 현재 실행중인 코드에 쉽게 액세스
- 유저 랜드 API
- SAPI 불가지론-쉽게 통합
- PHP 구성 파일 지원
- JIT Super Globals-나만의 설정 !!
- 선택적인 리드 라인 지원-편안한 터미널 작동
- 원격 디버깅 지원-번들 Java GUI
- 쉬운 조작
스크린 샷을 참조하십시오 :
홈페이지 : http://phpdbg.com/
PHP 오류-PHP에 대한 더 나은 오류보고
라이브러리 (실제 파일)를 사용하여 PHP 스크립트를 디버깅하는 것은 매우 쉽습니다.
당신이해야 할 유일한 것은 아래와 같이 하나의 파일을 포함시키는 것입니다 (코드의 시작 부분에) :
require('php_error.php');
\php_error\reportErrors();
그런 다음 모든 오류는 역 추적, 코드 컨텍스트, 함수 인수, 서버 변수 등과 같은 정보를 제공합니다. 예를 들면 다음과 같습니다.
특징은 다음과 같습니다.
- 사소한 사용, 그것은 단지 하나의 파일입니다
- 정상 및 아약시 요청에 대해 브라우저에 표시되는 오류
- AJAX 요청이 일시 중지되어 자동으로 다시 실행할 수 있습니다.
- 오류를 가능한 한 엄격하게 만듭니다 (코드 품질을 높이고 성능을 향상시키는 경향이 있음)
- 전체 스택 추적에서 코드 스 니펫
- 자세한 정보를 제공합니다 (예 : 전체 기능 서명).
- 평범한 오류 메시지 수정
- 구문 강조
- 예뻐요!
- 커스터마이징
- 수동으로 켜고 끄기
- 오류보고없이 특정 섹션을 실행
- 스택 추적에서 코드를 강조 표시하지 않도록 파일을 무시하십시오.
- 응용 프로그램 파일; 오류가 발생하면 우선 순위가 결정됩니다!
홈페이지 : http://phperror.net/
GitHub : https://github.com/JosephLenton/PHP-Error
내 포크 (추가 수정 사항) : https://github.com/kenorb-contrib/PHP-Error
DTrace
시스템이 DTrace 동적 추적 (OS X에 기본적으로 설치됨)을 지원 하고 기본적으로 --enable-dtrace
사용해야 하는 DTrace 프로브 ( )를 사용하여 PHP를 컴파일하는 경우이 명령을 사용하면 시간없이 PHP 스크립트를 디버깅 할 수 있습니다.
sudo dtrace -qn 'php*:::function-entry { printf("%Y: PHP function-entry:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }'
그래서 당신에 추가 된 다음과 같은 별칭을 부여 RC의 파일 (예를 들어 ~/.bashrc
, ~/.bash_aliases
) :
alias trace-php='sudo dtrace -qn "php*:::function-entry { printf(\"%Y: PHP function-entry:\t%s%s%s() in %s:%d\n\", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }"'
기억하기 쉬운 별칭으로 스크립트를 추적 할 수 있습니다 trace-php
.
다음은 고급 dtrace 스크립트입니다.에 저장 dtruss-php.d
하고 실행 가능하게 만들고 ( chmod +x dtruss-php.d
) 실행하십시오.
#!/usr/sbin/dtrace -Zs
# See: https://github.com/kenorb/dtruss-lamp/blob/master/dtruss-php.d
#pragma D option quiet
php*:::compile-file-entry
{
printf("%Y: PHP compile-file-entry:\t%s (%s)\n", walltimestamp, basename(copyinstr(arg0)), copyinstr(arg1));
}
php*:::compile-file-return
{
printf("%Y: PHP compile-file-return:\t%s (%s)\n", walltimestamp, basename(copyinstr(arg0)), basename(copyinstr(arg1)));
}
php*:::error
{
printf("%Y: PHP error message:\t%s in %s:%d\n", walltimestamp, copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2);
}
php*:::exception-caught
{
printf("%Y: PHP exception-caught:\t%s\n", walltimestamp, copyinstr(arg0));
}
php*:::exception-thrown
{
printf("%Y: PHP exception-thrown:\t%s\n", walltimestamp, copyinstr(arg0));
}
php*:::execute-entry
{
printf("%Y: PHP execute-entry:\t%s:%d\n", walltimestamp, basename(copyinstr(arg0)), (int)arg1);
}
php*:::execute-return
{
printf("%Y: PHP execute-return:\t%s:%d\n", walltimestamp, basename(copyinstr(arg0)), (int)arg1);
}
php*:::function-entry
{
printf("%Y: PHP function-entry:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2);
}
php*:::function-return
{
printf("%Y: PHP function-return:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2);
}
php*:::request-shutdown
{
printf("%Y: PHP request-shutdown:\t%s at %s via %s\n", walltimestamp, basename(copyinstr(arg0)), copyinstr(arg1), copyinstr(arg2));
}
php*:::request-startup
{
printf("%Y, PHP request-startup:\t%s at %s via %s\n", walltimestamp, basename(copyinstr(arg0)), copyinstr(arg1), copyinstr(arg2));
}
홈페이지 : GitHub의 dtruss-lamp
간단한 사용법은 다음과 같습니다.
- 다음을 실행하십시오
sudo dtruss-php.d
. - 다른 터미널에서 다음을 실행하십시오
php -r "phpinfo();"
..
이를 테스트하려면 다음을 통해 모든 docroot로 이동하여 index.php
PHP 내장 서버를 실행할 수 있습니다 .
php -S localhost:8080
그런 다음 http : // localhost : 8080 / 사이트에 액세스 하거나 편리한 포트를 선택할 수 있습니다. 거기에서 추적 출력을 보려면 일부 페이지에 액세스하십시오.
참고 : Dtrace는 기본적으로 OS X에서 사용할 수 있으며 Linux에서는 dtrace4linux 가 필요 하거나 다른 대안이 있는지 확인하십시오 .
See: Using PHP and DTrace at php.net
SystemTap
Alternatively check for SystemTap tracing by installing SystemTap SDT development package (e.g. yum install systemtap-sdt-devel
).
Here is example script (all_probes.stp
) for tracing all core PHP static probe points throughout the duration of a running PHP script with SystemTap:
probe process("sapi/cli/php").provider("php").mark("compile__file__entry") {
printf("Probe compile__file__entry\n");
printf(" compile_file %s\n", user_string($arg1));
printf(" compile_file_translated %s\n", user_string($arg2));
}
probe process("sapi/cli/php").provider("php").mark("compile__file__return") {
printf("Probe compile__file__return\n");
printf(" compile_file %s\n", user_string($arg1));
printf(" compile_file_translated %s\n", user_string($arg2));
}
probe process("sapi/cli/php").provider("php").mark("error") {
printf("Probe error\n");
printf(" errormsg %s\n", user_string($arg1));
printf(" request_file %s\n", user_string($arg2));
printf(" lineno %d\n", $arg3);
}
probe process("sapi/cli/php").provider("php").mark("exception__caught") {
printf("Probe exception__caught\n");
printf(" classname %s\n", user_string($arg1));
}
probe process("sapi/cli/php").provider("php").mark("exception__thrown") {
printf("Probe exception__thrown\n");
printf(" classname %s\n", user_string($arg1));
}
probe process("sapi/cli/php").provider("php").mark("execute__entry") {
printf("Probe execute__entry\n");
printf(" request_file %s\n", user_string($arg1));
printf(" lineno %d\n", $arg2);
}
probe process("sapi/cli/php").provider("php").mark("execute__return") {
printf("Probe execute__return\n");
printf(" request_file %s\n", user_string($arg1));
printf(" lineno %d\n", $arg2);
}
probe process("sapi/cli/php").provider("php").mark("function__entry") {
printf("Probe function__entry\n");
printf(" function_name %s\n", user_string($arg1));
printf(" request_file %s\n", user_string($arg2));
printf(" lineno %d\n", $arg3);
printf(" classname %s\n", user_string($arg4));
printf(" scope %s\n", user_string($arg5));
}
probe process("sapi/cli/php").provider("php").mark("function__return") {
printf("Probe function__return: %s\n", user_string($arg1));
printf(" function_name %s\n", user_string($arg1));
printf(" request_file %s\n", user_string($arg2));
printf(" lineno %d\n", $arg3);
printf(" classname %s\n", user_string($arg4));
printf(" scope %s\n", user_string($arg5));
}
probe process("sapi/cli/php").provider("php").mark("request__shutdown") {
printf("Probe request__shutdown\n");
printf(" file %s\n", user_string($arg1));
printf(" request_uri %s\n", user_string($arg2));
printf(" request_method %s\n", user_string($arg3));
}
probe process("sapi/cli/php").provider("php").mark("request__startup") {
printf("Probe request__startup\n");
printf(" file %s\n", user_string($arg1));
printf(" request_uri %s\n", user_string($arg2));
printf(" request_method %s\n", user_string($arg3));
}
Usage:
stap -c 'sapi/cli/php test.php' all_probes.stp
See: Using SystemTap with PHP DTrace Static Probes at php.net
+1 for print_r(). Use it to dump out the contents of an object or variable. To make it more readable, do it with a pre tag so you don't need to view source.
echo '<pre>';
print_r($arrayOrObject);
Also var_dump($thing) - this is very useful to see the type of subthings
Depending on the issue I like a combination of error_reporting(E_ALL) mixed with echo tests (to find the offending line/file the error happened in initally; you KNOW it's not always the line/file php tells you right?), IDE brace matching (to resolve "Parse error: syntax error, unexpected $end" issues), and print_r(); exit; dumps (real programmers view the source ;p).
You also can't beat phpdebug (check sourceforge) with "memory_get_usage();" and "memory_get_peak_usage();" to find the problem areas.
The integrated debuggers where you can watch the values of variable change as you step through code are really cool. They do, however, require software setup on the server and a certain amount of configuration on the client. Both of which require periodic maintenance to keep in good working order.
print_r은 쓰기 쉽고 모든 설정에서 작동하도록 보장됩니다.
일반적으로 파일에 저장하고 디버그 정보를 저장하며 결국 공통 바닥 글에 다시 인쇄 할 수있는 사용자 정의 로그 함수를 만듭니다.
이 유형의 디버깅이 반 자동화되도록 공통 Exception 클래스를 대체 할 수도 있습니다.
참고 URL : https://stackoverflow.com/questions/888/how-do-you-debug-php-scripts
'development' 카테고리의 다른 글
JavaScript 객체의 내용을 인쇄 하시겠습니까? (0) | 2020.02.21 |
---|---|
가장 좋아하는 언어에 대해 싫어하는 다섯 가지는 무엇입니까? (0) | 2020.02.21 |
정의 : HashSet이란 무엇입니까? (0) | 2020.02.21 |
Vim 80 열 레이아웃 문제 (0) | 2020.02.20 |
cp 명령으로 파일을 대상에 복사하는 데 필요한 폴더를 작성하는 방법 (0) | 2020.02.20 |