Отображение ошибок php xampp

Hey look at that, made a more insane error making code and it works… but why isn’t it showing all errors?

Probably you’re not getting any ‘simple’ errors like:

Parse error: syntax error, unexpected T_VARIABLE in .../.../index.php on line 6
#or
Warning: include(whateveryouwantedto.include): failed to open str(...)

But you do get things like:

Fatal error: Call to undefined method stdClass::Crap() in .../.../index.php on line 6

According to my thinking hat, this is because if you don’t disable logging in your PHP configuration the ‘simple’ errors will be sent ‘nowhere’. In other words: PHP is ‘helping’ you by not showing any errors because you either defined log_errors = On and/or error_log = 'php_errors.log' and it’s logging all ‘real’ errors but your’s just don’t cut it to the ‘real’ category.

If this doesn’t help, the thinking hat says: «It can’t f* remember, but I sure as heaven/hell know it is somewhere in the PHP or Apache config.»

Sure hope my thinking hat helped you out.

EDIT:
Tackling this problem might be to find and open php.ini, select all, delete/backspace, save (but keep open) (or save a copy somewhere). Then restart Apache. See if there’s any difference. If so, the php configuration is somewhere else. Restore the php file and search your computer or server from the root up for another php.ini.

Also I think you should make sure :

log_errors = Off
error_log = "./"
display_errors = On
error_reporting = E_ALL

Or in PHP :

error_reporting(E_ALL & E_STRICT);
ini_set('display_errors', '1');
ini_set('log_errors', '0');
ini_set('error_log', './');

In the current version I’ve just installed (8.0.11) the installer «forgets» to create the folder C:\xamppp\php\logs, perhaps by design but that is ApacheFriends for you😜. After creating the folder and restarting Apache the folder will be populated with a php_error_log file. No, not a php_error.log but php_error_log, becouse they are your friends.

Follow

Terminal

To keep seeing the last entry (much like *nix sh tail -f) use the following command:

Get-Content c:\xampp\php\logs\php_error_log -Wait

This will keep reading the file and display the last entries. Quite handy if you are debugging.

Code

You might be using vscode so why hot have the errors right at you finger tips. Create a file .vscode\tasks.json

{ 
  // See https://go.microsoft.com/fwlink/?LinkId=733558 
  // for the documentation about the tasks.json format 
  "version": "2.0.0", 
  "tasks": [ 
    { 
      "label": "Monitor php errors", 
      "type": "shell", 
      "command": "Get-Content -Wait c:\\xampp\\php\\logs\\php_error_log", 
      "runOptions": { 
        "runOn": "folderOpen" 
      } 
    } 
  ] 

and allow it to run on start. Make sure you work on a folder, not single files, but you were doing that already, weren’t you?

Эй, посмотри на это, сделал более безумный код ошибки, и он работает… но почему он не показывает все ошибки?

Вероятно, вы не получаете никаких «простых» ошибок, например:

Parse error: syntax error, unexpected T_VARIABLE in .../.../index.php on line 6
#or
Warning: include(whateveryouwantedto.include): failed to open str(...)

Но вы получаете такие вещи, как:

Fatal error: Call to undefined method stdClass::Crap() in .../.../index.php on line 6

Согласно моей мыслительной шляпе, это потому, что если вы не отключите ведение журнала в вашей конфигурации PHP, «простые» ошибки будут отправлены «нигде». Другими словами: PHP «помогает» вам, не отображая никаких ошибок, потому что вы либо определили log_errors = On, либо /t error_log = 'php_errors.log', и регистрировали все «реальные» ошибки, но просто не перерезали его в «настоящую» категорию,

Если это не помогает, мыслящая шляпа говорит: «Это не может запомнить, но я уверен, что небо/ад знают, что это где-то в конфигурации PHP или Apache».

Надеюсь, моя мыслящая шляпа помогла вам.

EDIT:
Решение этой проблемы может заключаться в том, чтобы найти и открыть php.ini, выбрать все, удалить/вернуться, сохранить (но держать открытым) (или сохранить копию где-нибудь). Затем перезапустите Apache. Посмотрите, есть ли разница. Если это так, конфигурация php находится где-то в другом месте. Восстановите файл php и найдите свой компьютер или сервер от корня до другого php.ini.

Также я думаю, вы должны убедиться:

log_errors = Off
error_log = "./"
display_errors = On
error_reporting = E_ALL

Или в PHP:

error_reporting(E_ALL & E_STRICT);
ini_set('display_errors', '1');
ini_set('log_errors', '0');
ini_set('error_log', './');

During the execution of a PHP application, it can generate a wide range of warnings and errors. For developers seeking to troubleshoot a misbehaving application, being able to check these errors is critical. Developers, on the other hand, frequently encounter difficulties when attempting to display errors from their PHP applications. Instead, their applications simply stop working.

First and foremost, you should be aware that with PHP, some errors prevent the script from being executed. Some errors, on the other hand, just display error messages with a warning. Then you’ll learn how to use PHP to show or hide all error reporting.

In PHP, there are four types of errors:

  1. Notice Error – When attempting to access an undefined index in a PHP code, an error occurs. The execution of the PHP code is not halted by the notice error. It just alerts you to the fact that there is an issue.
  2. Warning Error – The most common causes of warning errors are omitting a file or invoking a function with improper parameters. It’s comparable to seeing a mistake, but it doesn’t stop the PHP code from running. It just serves as a reminder that the script has a flaw.
  3. Fatal Error – When undefined functions and classes are called in a PHP code, a fatal error occurs. The PHP code is stopped and an error message is displayed when a fatal error occurs.
  4. Parse Error – When a syntax issue occurs in the script, it is referred to as a parse error. The execution of the PHP code is also stopped when a parse error occurs, and an error message is displayed.

You’ve come to the right place if you’re having troubles with your PHP web application and need to see all of the errors and warnings. We’ll go through all of the different ways to activate PHP errors and warnings in this tutorial.

  1. To Show All PHP Errors
  2. .htaccess Configuration to Show PHP Errors
  3. Enable Detailed Warnings and Notices
  4. In-depth with the error_reporting() function
  5. Use error_log() Function to Log PHP Error
  6. Use Web Server Configuration to Log PHP Errors
  7. Collect PHP Errors using Atatus

1. To Show All PHP Errors

Adding these lines to your PHP code file is the quickest way to output all PHP errors and warnings:

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

The ini_set() function will attempt to override the PHP ini file’s configuration.

The display_errors and display_startup_errors directives are just two of the options.

  1. The display_errors directive determines whether or not the errors are visible to the user. After development, the dispay_errors directive should usually be disabled.
  2. The display_startup_errors directive, on the other hand, is separate since display errors do not handle errors that occur during PHP’s startup sequence.

The official documentation contains a list of directives that can be overridden by the ini_set() function. Unfortunately, parsing problems such as missing semicolons or curly brackets will not be displayed by these two directives. The PHP ini configuration must be changed in this scenario.

To display all errors, including parsing errors, in xampp, make the following changes to the php.ini example file and restart the apache server.

display_errors = on

In the PHP.ini file, set the display errors directive to turn on. It will show all errors that can’t be seen by just calling the ini_set() function, such as syntax and parsing errors.

2. .htaccess Configuration to Show PHP Errors

The directory files are normally accessible to developers. The .htaccess file in the project’s root or public directory can also be used to enable or disable the directive for displaying PHP errors.

php_flag display_startup_errors on
php_flag display_errors on

.htaccess has directives for display_startup_errors and display_errors, similar to what will be added to the PHP code to show PHP errors. The benefit of displaying or silencing error messages in this way is that development and production can have separate .htaccess files, with production suppressing error displays.

You may want to adjust display_errors in .htaccess or your PHP.ini file depending on which files you have access to and how you handle deployments and server configurations. Many hosting companies won’t let you change the PHP.ini file to enable display errors.

3. Enable Detailed Warnings and Notices

Warnings that appear to not affect the application at first might sometimes result in fatal errors under certain circumstances. These warnings must be fixed because they indicate that the application will not function normally in certain circumstances. If these warnings result in a large number of errors, it would be more practical to hide the errors and only display the warning messages.

error_reporting(E_WARNING);

Showing warnings and hiding errors are as simple as adding a single line of code for a developer. The parameter for the error reporting function will be “E_WARNING | E_NOTICE” to display warnings and notifications. As bitwise operators, the error reporting function can accept E_ERROR, E_WARNING, E_PARSE, and E_NOTICE parameters.

For ease of reference, these constants are also detailed in the online PHP Manual.

To report all errors except notices, use the option «E_ALL & E_NOTICE,» where E_ALL refers to all of the error reporting function’s potential parameters.

4. In-depth with the error_reporting() Function

One of the first results when you browser «PHP errors» is a link to the error_reporting() function documentation.

The PHP error_reporting() function allows developers to choose which and how many errors should be displayed in their applications. Remember that this function will set the error reporting directive in the PHP ini configuration during runtime.

error_reporting(0);

The value zero should be supplied to the error_reporting() function to delete all errors, warnings, parse messages, and notices. This line of code would be impractical to include in each of the PHP files. It is preferable to disable report messages in the PHP ini file or the .htaccess file.

error_reporting(-1);

An integer value is also passed as an input to the error_reporting() function. In PHP, we may use this method to display errors. In PHP, there are many different types of errors. All PHP errors are represented by the -1 level. Even with new levels and constants, passing the value -1 will work in future PHP versions.

error_reporting(E_NOTICE);

Variables can be used even if they aren’t declared in PHP. This isn’t recommended because undeclared variables can create issues in the application when they’re utilized in loops and conditions.

This can also happen when the stated variable is spelled differently than the variable used in conditions or loops. These undeclared variables will be displayed in the web application if E_NOTICE is supplied in the error_reporting() function.

error_reporting(E_ALL & ~E_NOTICE);

You can filter which errors are displayed using the error_reporting() function. The “~” character stands for “not” or “no,” hence the parameter ~E_NOTICE indicates that notices should not be displayed.

In the code, keep an eye out for the letters «&» and «|.» The “&” symbol stands for “true for all,” whereas the “|” character stands for “true for either.” In PHP, these two characters have the same meaning: OR and AND.

5. Use error_log() Function to Log PHP Error

Error messages must not be displayed to end-users during production, but they must be logged for tracing purposes. The best approach to keep track of these error messages in a live web application is to keep track of them in log files.

The error_log() function, which accepts four parameters, provides a simple way to use log files. The first parameter, which contains information about the log errors or what should be logged, is the only one that must be provided. This function’s type, destination, and header parameters are all optional.

error_log("Whoosh!!! Something is wrong!", 0);

If the type option is not specified, it defaults to 0, which means that this log information will be appended to the web server’s log file.

error_log("Email this error to Justin!", 1, "Justin@mydomain.com");

The error logs supplied in the third parameter will be emailed using the type 1 parameter. To use this feature, the PHP ini must have a valid SMTP configuration to send emails.

Host, encryption type, username, password, and port are among the SMTP ini directives. This kind of error reporting is recommended for logging or notifying errors that must be corrected as soon as possible.

error_log("Write this error down to a file!", 3, "logs/php-errors.log");

Type 3 must be used to log messages in a different file established by the web server’s configuration. The third parameter specifies the log file’s location, which must be writable by the webserver. The log file’s location might be either a relative or absolute library to where this code is invoked.

You can also refer to the error_log() function documentation to know more.

6. Use Web Server Configuration to Log PHP Errors

The ideal technique to record errors is to define them in the web server configuration file, rather than modifying parameters in the .htaccess or adding lines in the PHP code to show errors.

ErrorLog "/var/log/apache2/my-website-error.log"

These files must be added to the virtual host of a specific HTML page or application in Apache, which is commonly found in the sites-available folder in Ubuntu or the httpd-vhosts file in Windows.

error_log /var/log/nginx/my-website-error.log;

The directive is just called error_log() in Nginx, as it is in Apache. The log files for both Apache and Nginx web servers must be writable by the webserver. Fortunately, the folders for the log files of these two web servers are already writable after installation.

7. Collect PHP Errors using Atatus

Atatus is an Application Performance Management (APM) solution that collects all requests to your PHP applications without requiring you to change your source code. However, the tool does more than just keep track of your application’s performance. Atatus’ ability to automatically gather all unhandled errors in your PHP application is one of its best features.

To fix PHP exceptions, gather all necessary information such as class, message, URL, request agent, version, and so on. Every PHP error is logged and captured with a full stack trace, with the precise line of source code marked, to make bug fixes easy.

Read the guide to know more about PHP Performance Monitoring.

All errors are automatically logged and structured in Atatus so that they can be easily viewed. Not only will Atatus show you what errors have happened, but it will also examine where and why they occurred. The logs also display the time and number of occurrences, making it much easier to focus on which issue to address.

Start your 14-day free trial of Atatus, right now!!!

Summary

When there is an issue with the PHP code, a PHP error occurs. Even something as simple as incorrect syntax or forgetting a semicolon can result in an error, prompting a notification. Alternatively, the cause could be more complicated, such as invoking an incorrect variable, which can result in a fatal error and cause your system to crash.

This tutorial has shown you several ways to enable and display all PHP errors and warnings. You can boost your ability to debug PHP issues by receiving error notifications fast and precisely.

Let us know what you think about displaying PHP errors in the below comment section.


Установка

Перед тем как установить Joomla на локальный компьютер, вы должны установить и настроить Web сервер на компьютере (Apache, MySql и PHP). Здесь будет рассмотрена установка пакета XAMPP, который содержит эти составляющие. Вы так же можете воспользоваться другими пакетами типа Denwer и т.п. или установить и настроить Apache, MySql, PHP самостоятельно.

Установка XAMPP на Windows

Последнюю версию XAMPP для Windows можно найти на официальном странице. На данной странице нужно найти ссылку «Installer», нажать ее, загрузить установочный файл (например, xampp-win32-1.7.4-VC6-installer.exe) в любую директорию на компьютере. Запустить загруженный файл, после чего должно появиться следующее окно

Устаноывка XAMPP 1

Нажимаем кнопку «Next»

Install-xamp2

Здесь нужно указать директорию, в которую будет производиться установка. Производители не рекомендуют устанавливать XAMPP в директорию «C:\Program Files», из-за отсутствия или недостаточного разрешения на запись в этой директории. Директория, которая ставиться по умолчанию вполне подойдет. Нажимаем «Next».

В этом диалоговом окне можно выбрать установку Apache и MySQL как сервисы, т.е. они будут запускаться автоматически при старте Windows. Нажимаем кнопку «Install».

Install-xamp_4

Установка прошла успешно нажимаем кнопку «Finish». После этого появиться диалоговое окно

Install-xamp_5

Вас поздравляют с успешной установкой и предлагают запустить контрольную панель XAMPP . Если нажать кнопку «Да», то откроется контрольная панель, которая выглядит следующим образом. 

Install-xamp_6

Через данную контрольную панель можно запускать и останавливать сервисы Apache и MySQL. Если они еще не запущены, нажимаем напротив них кнопку «Start».

Открываем браузер и набираем в адресной строке «http://localhost/», после чего должна открыться вступительная страница XAMPP.

xampp page

На данной странице можно почитать документацию (на русском пока нету), посмотреть сведения о PHP, запустить phpMyAdmin для просмотра баз данных и выполнять другие действие.

Настройка XAMPP

Смена корневой директории

По умолчанию директория для localhost будет «c:\xampp\htdocs\», именно в ней находятся файлы, которые отображают в браузере вступительную страница XAMPP. При необходимости ее можно изменить в настройках сервера Apache, но это делать не обязательно. Для изменения директории остановите сервер Apache, в файле C:\xampp\apache\conf\httpd.conf (этот файл отвечает за конфигурацию сервера) укажите путь к желаемой директории, где будет находиться корень сервера:

DocumentRoot "C:/xampp/htdocs"

и

<Directory "C:/xampp/htdocs">

Запустите сервер снова. Для проверки работы можно в этой директории создать какой-нибудь index.html или index.php файл и набрать в браузере адрес — http://localhost/, должно загрузиться содержимое этого файла. Если вы изменили директорию, доступ к phpMyAdmin останется тот же: http://localhost/phpmyadmin/

Установка уровня отображения ошибок для PHP

Изначально XAMPP сконфигурирован для разработчика, т.е. в браузере будут отображаться не только критические ошибки PHP, но и различного рода предупреждения, например, «Strict Standards: …», «Notice: …» и другие. Для изменения уровня отображения ошибок PHP нужно открыть файл «C:\xampp\php\php.ini» в любом редакторе и в нем поставить значение:

error_reporting = E_ALL

 При этом значении будут отображаться только критические ошибки PHP.

После внесения изменений в файл конфигурации PHP (php.ini) так же нужно перезагружать сервер Apache. В контрольной панели XAMPP напротив «Apache» нажать кнопку «Stop», если сервис уже запущен, дальше после остановки нажать кнопку «Start».

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Отношения между мужчиной и женщиной психология ошибки этапы
  • Отображение ошибок php ini
  • Отображение ошибок codeigniter
  • Отображение всех ошибок php htaccess
  • Отображается ошибка 404

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: