Development Tip

PHP에서 유용한 오류 메시지를 어떻게 얻을 수 있습니까?

yourdevel 2020. 10. 3. 12:06
반응형

PHP에서 유용한 오류 메시지를 어떻게 얻을 수 있습니까?


PHP로 프로그래밍하는 것이 상당히 답답합니다. 꽤 자주 스크립트를 실행하고 빈 화면이 나타납니다. 오류 메시지가없고 화면이 비어 있습니다. 원인은 간단한 구문 오류 (잘못된 대괄호, 세미콜론 누락), 실패한 함수 호출 또는 완전히 다른 것일 수 있습니다.

무엇이 잘못되었는지 파악하는 것은 매우 어렵습니다. 코드를 주석 처리하고 모든 곳에 "echo"문을 입력하는 등 문제를 좁히기 위해 노력합니다. 하지만 분명히 더 나은 방법이 있겠죠?.

그렇다면 PHP가 Java처럼 유용한 오류 메시지를 생성하도록하는 방법이 있습니까? 누구든지 좋은 PHP 디버깅 팁과 기술을 추천 할 수 있습니까?


구문 오류의 경우 php.ini에서 오류 표시를 활성화해야합니다. "고객"에게 오류 메시지가 표시되는 것을 원하지 않기 때문에 기본적으로이 기능은 꺼져 있습니다. 두 가지 지시문에 대한 정보는 PHP 문서 에서이 페이지확인하십시오 : error_reportingdisplay_errors. display_errors아마도 당신이 바꾸고 싶은 것입니다. php.ini를 수정할 수없는 경우 .htaccess 파일에 다음 줄을 추가 할 수도 있습니다.

php_flag  display_errors        on
php_value error_reporting       2039

error_reporting모든 오류를 얻으려면 PHP 버전에 대해 E_ALL 값 (Gumbo에서 언급했듯이)을 사용 하는 것이 좋습니다. 더 많은 정보

3 기타 항목 : (1) 모든 오류가 포함되므로 오류 로그 파일을 확인할 수 있습니다 (로깅이 비활성화되지 않은 경우). (2) 다음 두 줄을 추가하면 구문 오류가 아닌 오류를 디버그하는 데 도움이됩니다.

error_reporting(-1);
ini_set('display_errors', 'On');

(3) 또 다른 옵션은 PhpEd 와 같이 입력 할 때 오류를 확인하는 편집기를 사용하는 입니다. PhpEd는 또한 더 자세한 정보를 제공 할 수있는 디버거와 함께 제공됩니다. (PhpEd 디버거는 xdebug와 매우 유사하며 편집기에 직접 통합되므로 하나의 프로그램을 사용하여 모든 작업을 수행 할 수 있습니다.)

Cartman의 링크 도 매우 좋습니다. http://www.ibm.com/developerworks/library/os-debug/


다음은 모든 오류를 활성화합니다.

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

다음 링크도 참조하십시오.


디버깅 할 파일에 다음 줄을 포함 할 수 있습니다.

error_reporting(E_ALL);
ini_set('display_errors', '1');

이렇게하면 php.ini의 기본 설정이 무시되어 PHP가 오류를 로그에보고하게됩니다.


PHP 구성

php.ini의 2 개 항목 은 오류 출력을 나타냅니다.

  1. display_errors
  2. error_reporting

에서 생산 , display_errors일반적으로 설정됩니다 Off(생산 현장에서 에러 표시가 일반적으로 바람직하지 않기 때문에, 좋은 일 어느!).

그러나 개발On 중에는 오류가 표시되도록 로 설정해야합니다 . 확인 !

error_reporting(PHP 5.3부터) 기본적으로 E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED(알림, 엄격한 표준 및 지원 중단 알림을 제외한 모든 것이 표시됨 )로 설정됩니다 . 확실하지 않은 경우 모든 오류 E_ALL를 표시 하도록 설정하십시오 . 확인 !

워워! 확인 안돼! 내 php.ini를 변경할 수 없습니다!

부끄러운 일입니다. 일반적으로 공유 호스트는 php.ini 파일의 변경을 허용하지 않으므로이 옵션은 슬프게도 사용할 수 없습니다. 그러나 두려워하지 마십시오! 우리는 다른 옵션이 있습니다 !

런타임 구성

원하는 스크립트에서 런타임에 php.ini 항목을 변경할 수 있습니다! 즉, 스크립트가 실행될 때 실행됩니다! 단!

error_reporting(E_ALL);
ini_set("display_errors", "On");

이 두 줄은 위와 같이 php.ini 항목을 변경하는 것과 동일한 효과를냅니다! 대박!

여전히 빈 페이지 / 500 오류가 발생합니다!

즉, 스크립트가 실행되지 않았 음을 의미합니다! 일반적으로 구문 오류가있을 때 발생합니다!

구문 오류로 인해 스크립트가 런타임에 도달하지 않습니다. 컴파일 시간에 실패합니다 . 즉, 변경하지 않은 경우 오류 표시를 허용하지 않을 수있는 php.ini의 값을 사용합니다.

오류 로그

또한 PHP는 기본적으로 오류를 기록합니다. 공유 호스팅에서는 전용 폴더에 있거나 문제가있는 스크립트와 동일한 폴더에있을 수 있습니다.

php.ini에 액세스 할 수있는 경우 error_log항목 아래에서 찾을 수 있습니다 .


" xdebug " 라는 정말 유용한 확장 기능 이있어 보고서를 훨씬 더 멋지게 만들 수 있습니다.


빠른 실습 문제 해결을 위해 일반적으로 여기에서 제안합니다.

error_reporting(~0); ini_set('display_errors', 1);

문제 해결중인 스크립트의 시작 부분에 배치됩니다. 이것은 완벽하지 않습니다. 완벽한 변형은 php.ini구문 및 시작 오류를 포착하기 위해 PHP에서 오류를 활성화하고 PHP에 오류를 기록하는 것입니다.

여기에 설명 된 설정은 PHP 버전에 관계없이 엄격한 오류를 포함하여 모든 오류, 알림 및 경고를 표시합니다.

고려해야 할 다음 사항 :

  • Xdebug를 설치 하고 IDE로 원격 디버깅을 활성화합니다.

참조 :


당신이 정말 멋 있다면 다음을 시도해 볼 수 있습니다.

$test_server = $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost" || substr($_SERVER['SERVER_NAME'],0,3) == "192";

ini_set('display_errors',$test_server);
error_reporting(E_ALL|E_STRICT);

로컬에서 실행할 때만 오류가 표시됩니다. 또한 적절한 다른 위치에서 사용할 수있는 test_server 변수를 제공합니다.

스크립트가 실행되기 전에 발생하는 오류는 잡히지 않지만 내가 만드는 오류의 99 %에 대해서는 문제가되지 않습니다.


페이지 상단에서 매개 변수를 선택합니다.

error_reporting(E_ERROR | E_WARNING | E_PARSE);

이를 유지하고 편리하게 만들기 위해 php.ini 파일을 편집 할 수 있습니다. 일반적으로 /etc/php.ini또는에 저장 /etc/php/php.ini되지만 php.ini호스팅 제공 업체의 설정 지침에 따라 더 많은 로컬 파일 이 덮어 쓸 수 있습니다. 맨 위에 있는 phpinfo()파일을 확인하여 어떤 파일 Loaded Configuration File이 마지막으로로드되는지 확인하십시오.

해당 파일에서 display_errors를 검색합니다. 3 개의 인스턴스 만 있어야하며이 중 2 개는 주석 처리됩니다.

주석 처리되지 않은 줄을 다음과 같이 변경하십시오.

display_errors = stdout

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
ini_set('html_errors', 1);

또한 xdebug를 사용 하여 더 자세한 정보를 얻을 수 있습니다 .


PHP에서 오류와 예외를 더 잘 시각화하려면 Nette Tracy권장합니다 .

Nette Tracy 스크린 샷


error_reporting(E_ALL | E_STRICT);

그리고 php.ini에서 디스플레이 오류를 켭니다.


You can register your own error handler in PHP. Dumping all errors to a file might help you in these obscure cases, for example. Note that your function will get called, no matter what your current error_reporting is set to. Very basic example:

function dump_error_to_file($errno, $errstr) {
    file_put_contents('/tmp/php-errors', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
set_error_handler('dump_error_to_file');

FirePHP can be useful as well.


You might also want to try PHPStorm as your code editor. It will find many PHP and other syntax errors right as you are typing in the editor.


The two key lines you need to get useful errors out of PHP are:

ini_set('display_errors',1);
 error_reporting(E_ALL);

As pointed out by other contributors, these are switched off by default for security reasons. As a useful tip - when you're setting up your site it's handy to do a switch for your different environments so that these errors are ON by default in your local and development environments. This can be achieved with the following code (ideally in your index.php or config file so this is active from the start):

switch($_SERVER['SERVER_NAME'])
{
    // local
    case 'yourdomain.dev':
    // dev
    case 'dev.yourdomain.com':
        ini_set('display_errors',1);
        error_reporting(E_ALL);
    break;
    //live
    case 'yourdomain.com':
        //...
    break;
}

if you are a ubuntu user then goto your terminal and run this command

sudo tail -50f /var/log/apache2/error.log

where it will display recent 50 errors. There is a error file error.log for apache2 which logs all the errors.


You can enable full error reporting (including notices and strict messages). Some people find this too verbose, but it's worth a try. Set error_reporting to E_ALL | E_STRICT in your php.ini.

error_reporting = E_ALL | E_STRICT

E_STRICT will notify you about deprecated functions and give you recommendations about the best methods to do certain tasks.

If you don't want notices, but you find other message types helpful, try excluding notices:

error_reporting = (E_ALL | E_STRICT) & ~E_NOTICE

Also make sure that display_errors is enabled in php.ini. If your PHP version is older than 5.2.4, set it to On:

display_errors = "On"

If your version is 5.2.4 or newer, use:

display_errors = "stderr"

To turn on full error reporting, add this to your script:

error_reporting(E_ALL);

This causes even minimal warnings to show up. And, just in case:

ini_set('display_errors', '1');

Will force the display of errors. This should be turned off in production servers, but not when you're developing.


Aside from error_reporting and the display_errors ini setting, you can get SYNTAX errors from your web server's log files. When I'm developing PHP I load my development system's web server logs into my editor. Whenever I test a page and get a blank screen, the log file goes stale and my editor asks if I want to reload it. When I do, I jump to the bottom and there is the syntax error. For example:

[Sun Apr 19 19:09:11 2009] [error] [client 127.0.0.1] PHP Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\\webroot\\test\\test.php on line 9

The “ERRORS” are the most useful things for the developers to know their mistakes and resolved them to make the system working perfect.

PHP provides some of better ways to know the developers why and where their piece of code is getting the errors, so by knowing those errors developers can make their code better in many ways.

Best ways to write following two lines on the top of script to get all errors messages:

error_reporting(E_ALL);
ini_set("display_errors", 1);

Another way to use debugger tools like xdebug in your IDE.


In addition to all the wonderful answers here, I'd like to throw in a special mention for the MySQLi and PDO libraries.

In order to...

  1. Always see database related errors, and
  2. Avoid checking the return types for methods to see if something went wrong

The best option is to configure the libraries to throw exceptions.

MySQLi

Add this near the top of your script

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

This is best placed before you use new mysqli() or mysqli_connect().

PDO

Set the PDO::ATTR_ERRMODE attribute to PDO::ERRMODE_EXCEPTION on your connection instance. You can either do this in the constructor

$pdo = new PDO('driver:host=localhost;...', 'username', 'password', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

or after creation

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

This answer is brought to you by the department of redundancy department.

  1. ini_set() / php.ini / .htaccess / .user.ini

    The settings display_errors and error_reporting have been covered sufficiently now. But just to recap when to use which option:

    • ini_set() and error_reporting() apply for runtime errors only.
    • php.ini should primarily be edited for development setups. (Webserver and CLI version often have different php.ini's)
    • .htaccess flags only work for dated setups (Find a new hoster! Well managed servers are cheaper.)
    • .user.ini are partial php.ini's for modern setups (FCGI/FPM)

    And as crude alternative for runtime errors you can often use:

    set_error_handler("var_dump");   // ignores error_reporting and `@` suppression
    
  2. error_get_last()

    Can be used to retrieve the last runtime notice/warning/error, when error_display is disabled.

  3. $php_errormsg

    Is a superlocal variable, which also contains the last PHP runtime message.

  4. isset() begone!

    I know this will displease a lot of folks, but isset and empty should not be used by newcomers. You can add the notice suppression after you verified your code is working. But never before.

    A lot of the "something doesn't work" questions we get lately are the result of typos like:

    if(isset($_POST['sumbit']))
    #                  ↑↑
    

    You won't get any useful notices if your code is littered with isset/empty/array_keys_exists. It's sometimes more sensible to use @, so notices and warnings go to the logs at least.

  5. assert_options(ASSERT_ACTIVE|ASSERT_WARNING);

    To get warnings for assert() sections. (Pretty uncommon, but more proficient code might contain some.)

    PHP7 requires zend.assertions=1 in the php.ini as well.

  6. declare(strict_types=1);

    Bending PHP into a strictly typed language is not going to fix a whole lot of logic errors, but it's definitely an option for debugging purposes.

  7. PDO / MySQLi

    And @Phil already mentioned PDO/MySQLi error reporting options. Similar options exist for other database APIs of course.

  8. json_last_error() + json_last_error_msg

    For JSON parsing.

  9. preg_last_error()

    For regexen.

  10. CURLOPT_VERBOSE

    To debug curl requests, you need CURLOPT_VERBOSE at the very least.

  11. shell/exec()

    Likewise will shell command execution not yield errors on its own. You always need 2>&1 and peek at the $errno.


Turning on error reporting is the correct solution, however it does not seem to take effect in the program that turns it on, but only in subsequently included programs.

Thus, I always create a file/program (which I usually call "genwrap.php") which has essentially the same code as the popular solution here (ie. turn on error reporting) and it also then includes the page I actually want to call.

There are 2 steps to implement this debugging;

One - create genwrap.php and put this code in it:

<?php
error_reporting(-1);
ini_set('display_errors', 'On');

include($_REQUEST['page']);
?>

Two - change the link to the program/page you want to debug to go via genwrap.php,

Eg: change:

$.ajax('dir/pgm.php?param=val').done(function(data) { /* ... */

to

$.ajax('dir/genwrap.php?page=pgm.php&param=val').done(function(data) { /* ... */

In addition to the very many excellent answers above you could also implement the following two functions in your projects. They will catch every non-syntax error before application/script exit. Inside the functions you can do a backtrace and log or render a pleasant 'Site is under maintenance' message to the public.

Fatal Errors:

register_shutdown_function

http://php.net/manual/en/function.register-shutdown-function.php

오류 :

set_error_handler

http://php.net/manual/en/function.set-error-handler.php

역 추적 :

debug_backtrace

http://php.net/manual/en/function.debug-backtrace.php

참고 URL : https://stackoverflow.com/questions/845021/how-can-i-get-useful-error-messages-in-php

반응형