Меню

Nginx вывод ошибок php

Error Reporting Itself

ini_set('display_errors', 1); or display_errors

Simply allows PHP to output errors — useful for debugging, highly recommended to disable for production environments. It often contains information you’d never want users to see.

error_reporting(E_ALL); or error_reporting

Simply sets exactly which errors are shown.

Setting one or the other will not guarantee that errors will be displayed. You must set both to actually see errors on your screen.

As for setting this up permanently inside your PHP config, the default for error_reporting is E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED. That said, this variable should not need changed. See here:

http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting

As for displaying errors, see here:

http://php.net/manual/en/errorfunc.configuration.php#ini.display-errors

Set the config value of «display_errors» to either stderr or stdout, depending on your need.

Just change these variables inside of your php.ini file and you’ll be golden. Make absolutely sure both display_errors and error_reporting is set to a satisfactory value. Just setting error_reporting will not guarantee that you see the errors you’re looking for!


Error Reporting Works Everywhere Except When Connecting To My DB!

If you see errors everywhere you need to except in the Database Connection, you just need to do some error catching. If it’s PDO, do something like this:

try {
    $this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $this->DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $STH = $this->DBH->prepare("INSERT INTO `" . $this->table . "` ($fs) value ($ins) $up");
            
    $STH->execute($data);
            
    $id = $this->DBH->lastInsertId();
            
    $this->closeDb();
            
    return $id;
} catch(PDOException $e) {
    echo $e->getMessage();
}

Just a snippet from my framework. Of course you’ll have to change it to your liking, but you should be able to get the general idea there. They key is this part here:

try {
    //DB Stuff
} catch(PDOException $e) {
    echo $e->getMessage();
}

I Still Don’t See The Error

If you’ve done both of what I’ve listed here and still have trouble, your problem has nothing to do with enabling error reporting. The code provided will show you the error with a Database Connection itself, and inside of PHP code. You must have a completely different issue if this has not shown you an error you’re chasing.

You’ll likely need to be a bit more descriptive on exactly what you’re chasing, and what you’re expecting to see.

Содержание

  1. Как настроить отображение ошибок в PHP
  2. Как быстро показать все ошибки PHP
  3. Что именно делают эти строки?
  4. Отображение ошибок PHP через настройки в php.ini
  5. Отображать ошибки PHP через настройки в .htaccess
  6. Включить подробные предупреждения и уведомления
  7. Более подробно о функции error_reporting ()
  8. Включить ошибки php в файл с помощью функции error_log ()
  9. Журнал ошибок PHP через конфигурацию веб-сервера

Как настроить отображение ошибок в PHP

В этом руководстве мы расскажем о различных способах того, как в PHP включить вывод ошибок. Мы также обсудим, как записывать ошибки в журнал (лог).

Как быстро показать все ошибки PHP

Самый быстрый способ отобразить все ошибки и предупреждения php — добавить эти строки в файл PHP:

Что именно делают эти строки?

Функция ini_set попытается переопределить конфигурацию, найденную в вашем ini-файле PHP.

Display_errors и display_startup_errors — это только две из доступных директив. Директива display_errors определяет, будут ли ошибки отображаться для пользователя. Обычно директива dispay_errors не должна использоваться для “боевого” режима работы сайта, а должна использоваться только для разработки.

display_startup_errors — это отдельная директива, потому что display_errors не обрабатывает ошибки, которые будут встречаться во время запуска PHP. Список директив, которые могут быть переопределены функцией ini_set, находится в официальной документации .

К сожалению, эти две директивы не смогут отображать синтаксические ошибки, такие как пропущенные точки с запятой или отсутствующие фигурные скобки.

Отображение ошибок PHP через настройки в php.ini

Если ошибки в браузере по-прежнему не отображаются, то добавьте директиву:

Директиву display_errors следует добавить в ini-файл PHP. Она отобразит все ошибки, включая синтаксические ошибки, которые невозможно отобразить, просто вызвав функцию ini_set в коде PHP.

Актуальный INI-файл можно найти в выводе функции phpinfo (). Он помечен как “загруженный файл конфигурации” (“loaded configuration file”).

Отображать ошибки PHP через настройки в .htaccess

Включить или выключить отображение ошибок можно и с помощью файла .htaccess, расположенного в каталоге сайта.

.htaccess также имеет директивы для display_startup_errors и display_errors.

Вы можете настроить display_errors в .htaccess или в вашем файле PHP.ini. Однако многие хостинг-провайдеры не разрешают вам изменять ваш файл PHP.ini для включения display_errors.

В файле .htaccess также можно включить настраиваемый журнал ошибок, если папка журнала или файл журнала доступны для записи. Файл журнала может быть относительным путем к месту расположения .htaccess или абсолютным путем, например /var/www/html/website/public/logs .

Включить подробные предупреждения и уведомления

Иногда предупреждения приводят к некоторым фатальным ошибкам в определенных условиях. Скрыть ошибки, но отображать только предупреждающие (warning) сообщения можно вот так:

Для отображения предупреждений и уведомлений укажите «E_WARNING | E_NOTICE».

Также можно указать E_ERROR, E_WARNING, E_PARSE и E_NOTICE в качестве аргументов. Чтобы сообщить обо всех ошибках, кроме уведомлений, укажите «E_ALL &

E_NOTICE», где E_ALL обозначает все возможные параметры функции error_reporting.

Более подробно о функции error_reporting ()

Функция сообщения об ошибках — это встроенная функция PHP, которая позволяет разработчикам контролировать, какие ошибки будут отображаться. Помните, что в PHP ini есть директива error_reporting, которая будет задана ​​этой функцией во время выполнения.

Для удаления всех ошибок, предупреждений, сообщений и уведомлений передайте в функцию error_reporting ноль. Можно сразу отключить сообщения отчетов в ini-файле PHP или в .htaccess:

PHP позволяет использовать переменные, даже если они не объявлены. Это не стандартная практика, поскольку необъявленные переменные будут вызывать проблемы для приложения, если они используются в циклах и условиях.

Иногда это также происходит потому, что объявленная переменная имеет другое написание, чем переменная, используемая для условий или циклов. Когда E_NOTICE передается в функцию error_reporting, эти необъявленные переменные будут отображаться.

Функция сообщения об ошибках позволяет вам фильтровать, какие ошибки могут отображаться. Символ «

» означает «нет», поэтому параметр

E_NOTICE означает не показывать уведомления. Обратите внимание на символы «&» и «|» между возможными параметрами. Символ «&» означает «верно для всех», в то время как символ «|» представляет любой из них, если он истинен. Эти два символа имеют одинаковое значение в условиях PHP OR и AND.

Эти три строки кода делают одно и то же, они будут отображать все ошибки PHP. Error_reporting(E_ALL) наиболее широко используется разработчиками для отображения ошибок, потому что он более читабелен и понятен.

Включить ошибки php в файл с помощью функции error_log ()

У сайта на хостинге сообщения об ошибках не должны показываться конечным пользователям, но эта информация все равно должна быть записана в журнал (лог).

Простой способ использовать файлы журналов — использовать функцию error_log, которая принимает четыре параметра. Единственный обязательный параметр — это первый параметр, который содержит подробную информацию об ошибке или о том, что нужно регистрировать. Тип, назначение и заголовок являются необязательными параметрами.

Параметр type, если он не определен, будет по умолчанию равен 0, что означает, что эта информация журнала будет добавлена ​​к любому файлу журнала, определенному на веб-сервере.

Параметр 1 отправит журнал ошибок на почтовый ящик, указанный в третьем параметре. Чтобы эта функция работала, PHP ini должен иметь правильную конфигурацию SMTP, чтобы иметь возможность отправлять электронные письма. Эти SMTP-директивы ini включают хост, тип шифрования, имя пользователя, пароль и порт. Этот вид отчетов рекомендуется использовать для самых критичных ошибок.

Для записи сообщений в отдельный файл необходимо использовать тип 3. Третий параметр будет служить местоположением файла журнала и должен быть доступен для записи веб-сервером. Расположение файла журнала может быть относительным путем к тому, где этот код вызывается, или абсолютным путем.

Журнал ошибок PHP через конфигурацию веб-сервера

Лучший способ регистрировать ошибки — это определить их в файле конфигурации веб-сервера.

Однако в этом случае вам нужно попросить администратора сервера добавить следующие строки в конфигурацию.

Пример для Apache:

В nginx директива называется error_log.

Теперь вы знаете, как в PHP включить отображение ошибок. Надеемся, что эта информация была вам полезна.

Источник

When accessing some PHP scripts on my website, I’m getting the dreaded 500 error message. I’d like to know what’s wrong to fix it, but Nginx isn’t logging any PHP errors in the log file I have specified. This is my server block:

server {
    listen 80;
    server_name localhost;
    access_log /home/whitey/sites/localhost/logs/access.log;
    error_log /home/whitey/sites/localhost/logs/error.log error;
    root /home/whitey/sites/localhost/htdocs;
    index index.html index.php /index.php;

    location / { 

    }

    location ~ .php$ {
        fastcgi_pass unix:/tmp/phpfpm.sock;
        fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~* .(?:ico|css|js|gif|jpe?g|png)$ {
        expires max;
    }
}

Note that some PHP scripts work fine, and others don’t. So there isn’t a global problem with PHP, there’s just something in these scripts that’s causing Nginx to throw the 500 error.

How can I get to the bottom of this? The only thing in error.log is an error about favicon.ico not being found.

asked Aug 13, 2012 at 18:30

James Linton's user avatar

4

You have to add the following to your php-fpm pool configurations:

catch_workers_output = 1

You have to add this line to each defined pool!

answered Aug 20, 2012 at 23:21

Fleshgrinder's user avatar

FleshgrinderFleshgrinder

3,7082 gold badges16 silver badges20 bronze badges

1

I had a similar issue.

I tried deploy phpMyAdmin with php-fpm 7.0 and nginx on CentOS7. Nginx showed me 500.html but there was not errors in any log file.
I did all of this

catch_workers_output = 1

and

display_errors = On

Either nginx log or php-fpm log did not contained any error string.

And when I commented this line in nginx.conf I was able to see in browser page things that was wrong.

#    error_page 500 502 503 504 /50x.html;
#    location = /50x.html {
#    }

That was what helped me understand troubles.

answered Jul 13, 2017 at 12:20

venoel's user avatar

venoelvenoel

1837 bronze badges

php-fpm throws everything in /var/log/php5-fpm.log
or similar.

answered Aug 13, 2012 at 18:37

erickzetta's user avatar

erickzettaerickzetta

5892 silver badges4 bronze badges

6

Look in your nginx.conf for an error_log definition. Maybe nginx writes something in this error log.

You might also enable logging to file on PHP.

answered Aug 13, 2012 at 18:36

Christopher Perrin's user avatar

1

For me, this seemed to be a problem with upstart, which was routing the logs for php-fpm to it’s own custom location, e.g.:

/var/log/upstart/php5-fpm.log

There’s also some bugginess with ubuntu Precise, 12.04 that may contribute to the lack of logging ability: https://bugs.php.net/bug.php?id=61045 If you’re still running that version.

answered Jul 21, 2015 at 16:55

Kzqai's user avatar

KzqaiKzqai

1,2784 gold badges18 silver badges32 bronze badges

When PHP display_errors are disabled, PHP errors can return Nginx 500 error.

You should take a look to your php-fpm logs, i’m sure you’ll find the error there. With CentOS 7 :

tail -f /var/log/php-fpm/www-error.log

You can also show PHP errors. In your php.ini, change :

display_errors = Off

to :

display_errors = On

Hope it helps.

answered Jan 22, 2016 at 0:34

Antoine Martin's user avatar

This is what happened to me:

When I deleted my error log, nginx noticed that it was no longer missing. When I recreated this file nginx would no longer recognise that it existed, therefore not writing to the file.

To fix this, run these commands (I’m on Ubuntu 14.04 LTS):

sudo service nginx reload

If that doesn’t work, then try:

sudo service nginx restart

answered Aug 12, 2015 at 7:22

dspacejs's user avatar

dspacejsdspacejs

1111 silver badge3 bronze badges

4

The behaviour of these functions is affected by settings in php.ini.

Errors and Logging Configuration Options

Name Default Changeable Changelog
error_reporting NULL PHP_INI_ALL  
display_errors «1» PHP_INI_ALL  
display_startup_errors «1» PHP_INI_ALL Prior to PHP 8.0.0, the default value was "0".
log_errors «0» PHP_INI_ALL  
log_errors_max_len «1024» PHP_INI_ALL  
ignore_repeated_errors «0» PHP_INI_ALL  
ignore_repeated_source «0» PHP_INI_ALL  
report_memleaks «1» PHP_INI_ALL  
track_errors «0» PHP_INI_ALL Deprecated as of PHP 7.2.0, removed as of PHP 8.0.0.
html_errors «1» PHP_INI_ALL  
xmlrpc_errors «0» PHP_INI_SYSTEM  
xmlrpc_error_number «0» PHP_INI_ALL  
docref_root «» PHP_INI_ALL  
docref_ext «» PHP_INI_ALL  
error_prepend_string NULL PHP_INI_ALL  
error_append_string NULL PHP_INI_ALL  
error_log NULL PHP_INI_ALL  
error_log_mode 0o644 PHP_INI_ALL Available as of PHP 8.2.0
syslog.facility «LOG_USER» PHP_INI_SYSTEM Available as of PHP 7.3.0.
syslog.filter «no-ctrl» PHP_INI_ALL Available as of PHP 7.3.0.
syslog.ident «php» PHP_INI_SYSTEM Available as of PHP 7.3.0.

For further details and definitions of the
PHP_INI_* modes, see the Where a configuration setting may be set.

Here’s a short explanation of
the configuration directives.

error_reporting
int

Set the error reporting level. The parameter is either an integer
representing a bit field, or named constants. The error_reporting
levels and constants are described in
Predefined Constants,
and in php.ini. To set at runtime, use the
error_reporting() function. See also the
display_errors directive.

The default value is E_ALL.

Prior to PHP 8.0.0, the default value was:
E_ALL &
~E_NOTICE &
~E_STRICT &
~E_DEPRECATED
.
This means diagnostics of level E_NOTICE,
E_STRICT and E_DEPRECATED
were not shown.

Note:
PHP Constants outside of PHP

Using PHP Constants outside of PHP, like in httpd.conf,
will have no useful meaning so in such cases the int values
are required. And since error levels will be added over time, the maximum
value (for E_ALL) will likely change. So in place of
E_ALL consider using a larger value to cover all bit
fields from now and well into the future, a numeric value like
2147483647 (includes all errors, not just
E_ALL).

display_errors
string

This determines whether errors should be printed to the screen
as part of the output or if they should be hidden from the user.

Value "stderr" sends the errors to stderr
instead of stdout.

Note:

This is a feature to support your development and should never be used
on production systems (e.g. systems connected to the internet).

Note:

Although display_errors may be set at runtime (with ini_set()),
it won’t have any effect if the script has fatal errors.
This is because the desired runtime action does not get executed.

display_startup_errors
bool

Even when display_errors is on, errors that occur during PHP’s startup
sequence are not displayed. It’s strongly recommended to keep
display_startup_errors off, except for debugging.

log_errors
bool

Tells whether script error messages should be logged to the
server’s error log or error_log.
This option is thus server-specific.

Note:

You’re strongly advised to use error logging in place of
error displaying on production web sites.

log_errors_max_len
int

Set the maximum length of log_errors in bytes. In
error_log information about
the source is added. The default is 1024 and 0 allows to not apply
any maximum length at all.
This length is applied to logged errors, displayed errors and also to
$php_errormsg, but not to explicitly called functions
such as error_log().

When an int is used, the
value is measured in bytes. Shorthand notation, as described
in this FAQ, may also be used.

ignore_repeated_errors
bool

Do not log repeated messages. Repeated errors must occur in the same
file on the same line unless
ignore_repeated_source
is set true.

ignore_repeated_source
bool

Ignore source of message when ignoring repeated messages. When this setting
is On you will not log errors with repeated messages from different files or
sourcelines.

report_memleaks
bool

If this parameter is set to On (the default), this parameter will show a
report of memory leaks detected by the Zend memory manager. This report
will be sent to stderr on Posix platforms. On Windows, it will be sent
to the debugger using OutputDebugString() and can be viewed with tools
like » DbgView.
This parameter only has effect in a debug build and if
error_reporting includes E_WARNING in the allowed
list.

track_errors
bool

If enabled, the last error message will always be present in the
variable $php_errormsg.

html_errors
bool

If enabled, error messages will include HTML tags. The format for HTML
errors produces clickable messages that direct the user to a page
describing the error or function in causing the error. These references
are affected by
docref_root and
docref_ext.

If disabled, error message will be solely plain text.

xmlrpc_errors
bool

If enabled, turns off normal error reporting and formats errors as
XML-RPC error message.

xmlrpc_error_number
int

Used as the value of the XML-RPC faultCode element.

docref_root
string

The new error format contains a reference to a page describing the error or
function causing the error. In case of manual pages you can download the
manual in your language and set this ini directive to the URL of your local
copy. If your local copy of the manual can be reached by "/manual/"
you can simply use docref_root=/manual/. Additional you have
to set docref_ext to match the fileextensions of your copy
docref_ext=.html. It is possible to use external
references. For example you can use
docref_root=http://manual/en/ or
docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon
&url=http%3A%2F%2Fwww.php.net%2F"

Most of the time you want the docref_root value to end with a slash "/".
But see the second example above which does not have nor need it.

Note:

This is a feature to support your development since it makes it easy to
lookup a function description. However it should never be used on
production systems (e.g. systems connected to the internet).

docref_ext
string

See docref_root.

Note:

The value of docref_ext must begin with a dot ".".

error_prepend_string
string

String to output before an error message.
Only used when the error message is displayed on screen. The main purpose
is to be able to prepend additional HTML markup to the error message.

error_append_string
string

String to output after an error message.
Only used when the error message is displayed on screen. The main purpose
is to be able to append additional HTML markup to the error message.

error_log
string

Name of the file where script errors should be logged. The file should
be writable by the web server’s user. If the
special value syslog is used, the errors
are sent to the system logger instead. On Unix, this means
syslog(3) and on Windows it means the event log. See also:
syslog().
If this directive is not set, errors are sent to the SAPI error logger.
For example, it is an error log in Apache or stderr
in CLI.
See also error_log().

error_log_mode
int

File mode for the file described set in
error_log.

syslog.facility
string

Specifies what type of program is logging the message.
Only effective if error_log is set to «syslog».

syslog.filter
string

Specifies the filter type to filter the logged messages. Allowed
characters are passed unmodified; all others are written in their
hexadecimal representation prefixed with x.

  • all – the logged string will be split
    at newline characters, and all characters are passed unaltered
  • ascii – the logged string will be split
    at newline characters, and any non-printable 7-bit ASCII characters will be escaped
  • no-ctrl – the logged string will be split
    at newline characters, and any non-printable characters will be escaped
  • raw – all characters are passed to the system
    logger unaltered, without splitting at newlines (identical to PHP before 7.3)

This setting will affect logging via error_log set to «syslog» and calls to syslog().

Note:

The raw filter type is available as of PHP 7.3.8 and PHP 7.4.0.


This directive is not supported on Windows.

syslog.ident
string

Specifies the ident string which is prepended to every message.
Only effective if error_log is set to «syslog».

cjakeman at bcs dot org

13 years ago


Using

<?php ini_set('display_errors', 1); ?>

at the top of your script will not catch any parse errors. A missing ")" or ";" will still lead to a blank page.

This is because the entire script is parsed before any of it is executed. If you are unable to change php.ini and set

display_errors On

then there is a possible solution suggested under error_reporting:

<?php

error_reporting
(E_ALL);

ini_set("display_errors", 1);

include(
"file_with_errors.php");

?>

[Modified by moderator]

You should also consider setting error_reporting = -1 in your php.ini and display_errors = On if you are in development mode to see all fatal/parse errors or set error_log to your desired file to log errors instead of display_errors in production (this requires log_errors to be turned on).


ohcc at 163 dot com

6 years ago


If you set the error_log directive to a relative path, it is a path relative to the document root rather than php's containing folder.

iio7 at protonmail dot com

1 year ago


It's important to note that when display_errors is "on", PHP will send a HTTP 200 OK status code even when there is an error. This is not a mistake or a wrong behavior, but is because you're asking PHP to output normal HTML, i.e. the error message, to the browser.

When display_errors is set to "off", PHP will send a HTTP 500 Internal Server Error, and let the web server handle it from there. If the web server is setup to intercept FastCGI errors (in case of NGINX), it will display the 500 error page it has setup. If the web server cannot intercept FastCGI errors, or it isn't setup to do it, an empty screen will be displayed in the browser (the famous white screen of death).

If you need a custom error page but cannot intercept PHP errors on the web server you're using, you can use PHPs custom error and exception handling mechanism. If you combine that with output buffering you can prevent any output to reach the client before the error/exception occurs. Just remember that parse errors are compile time errors that cannot be handled by a custom handler, use "php -l foo.php" from the terminal to check for parse errors before putting your files on production.


Roger

3 years ago


When `error_log` is set to a file path, log messages will automatically be prefixed with timestamp [DD-MMM-YYYY HH:MM:SS UTC].  This appears to be hard-coded, with no formatting options.

php dot net at sp-in dot dk

8 years ago


There does not appear to be a way to set a tag / ident / program for log entries in the ini file when using error_log=syslog.  When I test locally, "apache2" is used.
However, calling openlog() with an ident parameter early in your script (or using an auto_prepend_file) will make PHP use that value for all subsequent log entries. closelog() will restore the original tag.

This can be done for setting facility as well, although the original value does not seem to be restored by closelog().


jaymore at gmail dot com

6 years ago


Document says
So in place of E_ALL consider using a larger value to cover all bit fields from now and well into the future, a numeric value like 2147483647 (includes all errors, not just E_ALL).

But it is better to set "-1" as the E_ALL value.
For example, in httpd.conf or .htaccess, use
php_value error_reporting -1
to report all kind of error without be worried by the PHP version.


This always works for me:

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

However, this doesn’t make PHP to show parse errors — the only way to show those errors is to modify your php.ini with this line:

display_errors = on

(if you don’t have access to php.ini, then putting this line in .htaccess might work too):

php_flag display_errors 1

anthonyryan1's user avatar

anthonyryan1

4,6472 gold badges33 silver badges27 bronze badges

answered Jan 29, 2014 at 11:25

Fancy John's user avatar

Fancy JohnFancy John

37.4k3 gold badges26 silver badges25 bronze badges

16

You can’t catch parse errors when enabling error output at runtime, because it parses the file before actually executing anything (and since it encounters an error during this, it won’t execute anything). You’ll need to change the actual server configuration so that display_errors is on and the approriate error_reporting level is used. If you don’t have access to php.ini, you may be able to use .htaccess or similar, depending on the server.

This question may provide additional info.

Community's user avatar

answered Jun 27, 2009 at 19:14

Michael Madsen's user avatar

Michael MadsenMichael Madsen

53.8k7 gold badges72 silver badges83 bronze badges

0

Inside your php.ini:

display_errors = on

Then restart your web server.

j0k's user avatar

j0k

22.4k28 gold badges80 silver badges88 bronze badges

answered Jan 8, 2013 at 9:27

user1803477's user avatar

user1803477user1803477

1,5951 gold badge9 silver badges4 bronze badges

5

To display all errors you need to:

1. Have these lines in the PHP script you’re calling from the browser (typically index.php):

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

2.(a) Make sure that this script has no syntax errors

—or—

2.(b) Set display_errors = On in your php.ini

Otherwise, it can’t even run those 2 lines!

You can check for syntax errors in your script by running (at the command line):

php -l index.php

If you include the script from another PHP script then it will display syntax errors in the included script. For example:

index.php

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

// Any syntax errors here will result in a blank screen in the browser

include 'my_script.php';

my_script.php

adjfkj // This syntax error will be displayed in the browser

answered Jan 29, 2014 at 9:52

andre's user avatar

andreandre

1,8311 gold badge16 silver badges8 bronze badges

2

Some web hosting providers allow you to change PHP parameters in the .htaccess file.

You can add the following line:

php_value display_errors 1

I had the same issue as yours and this solution fixed it.

Peter Mortensen's user avatar

answered May 18, 2013 at 15:01

Kalhua's user avatar

KalhuaKalhua

5614 silver badges2 bronze badges

1

You might find all of the settings for «error reporting» or «display errors» do not appear to work in PHP 7. That is because error handling has changed. Try this instead:

try{
     // Your code
} 
catch(Error $e) {
    $trace = $e->getTrace();
    echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}

Or, to catch exceptions and errors in one go (this is not backward compatible with PHP 5):

try{
     // Your code
} 
catch(Throwable $e) {
    $trace = $e->getTrace();
    echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}

answered Mar 28, 2016 at 19:26

Frank Forte's user avatar

Frank ForteFrank Forte

1,89718 silver badges18 bronze badges

9

This will work:

<?php
     error_reporting(E_ALL);
     ini_set('display_errors', 1);    
?>

Peter Mortensen's user avatar

answered May 5, 2014 at 13:23

Mahendra Jella's user avatar

Mahendra JellaMahendra Jella

5,2801 gold badge32 silver badges38 bronze badges

1

Use:

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

This is the best way to write it, but a syntax error gives blank output, so use the console to check for syntax errors. The best way to debug PHP code is to use the console; run the following:

php -l phpfilename.php

Peter Mortensen's user avatar

answered May 4, 2016 at 19:14

Abhijit Jagtap's user avatar

Abhijit JagtapAbhijit Jagtap

2,6852 gold badges32 silver badges43 bronze badges

0

Set this in your index.php file:

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

Peter Mortensen's user avatar

answered Sep 26, 2017 at 12:32

Sumit Gupta's user avatar

Sumit GuptaSumit Gupta

5694 silver badges12 bronze badges

0

Create a file called php.ini in the folder where your PHP file resides.

Inside php.ini add the following code (I am giving an simple error showing code):

display_errors = on

display_startup_errors = on

Peter Mortensen's user avatar

answered Mar 31, 2015 at 18:38

NavyaKumar's user avatar

NavyaKumarNavyaKumar

5895 silver badges3 bronze badges

As we are now running PHP 7, answers given here are not correct any more. The only one still OK is the one from Frank Forte, as he talks about PHP 7.

On the other side, rather than trying to catch errors with a try/catch you can use a trick: use include.

Here three pieces of code:

File: tst1.php

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 'On');
    // Missing " and ;
    echo "Testing
?>

Running this in PHP 7 will show nothing.

Now, try this:

File: tst2.php

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 'On');
    include ("tst3.php");
?>

File: tst3.php

<?php
    // Missing " and ;
    echo "Testing
?>

Now run tst2 which sets the error reporting, and then include tst3. You will see:

Parse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in tst3.php on line 4

Peter Mortensen's user avatar

answered May 20, 2017 at 12:07

Peter's user avatar

PeterPeter

1,23318 silver badges32 bronze badges

2

I would usually go with the following code in my plain PHP projects.

if(!defined('ENVIRONMENT')){
    define('ENVIRONMENT', 'DEVELOPMENT');
}

$base_url = null;

if (defined('ENVIRONMENT'))
{
    switch (ENVIRONMENT)
    {
        case 'DEVELOPMENT':
            $base_url = 'http://localhost/product/';
            ini_set('display_errors', 1);
            ini_set('display_startup_errors', 1);
            error_reporting(E_ALL|E_STRICT);
            break;

        case 'PRODUCTION':
            $base_url = 'Production URL'; /* https://google.com */
            error_reporting(0);
            /* Mechanism to log errors */
            break;

        default:
            exit('The application environment is not set correctly.');
    }
}

answered Feb 1, 2017 at 7:16

Channaveer Hakari's user avatar

If, despite following all of the above answers (or you can’t edit your php.ini file), you still can’t get an error message, try making a new PHP file that enables error reporting and then include the problem file. eg:

error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('problem_file.php');

Despite having everything set properly in my php.ini file, this was the only way I could catch a namespace error. My exact scenario was:

//file1.php
namespace ab;
class x {
    ...
}

//file2.php
namespace cd;
use cdx; //Dies because it's not sure which 'x' class to use
class x {
    ...
}

answered Apr 24, 2015 at 2:55

jxmallett's user avatar

jxmallettjxmallett

4,0471 gold badge28 silver badges35 bronze badges

2

If you somehow find yourself in a situation where you can’t modifiy the setting via php.ini or .htaccess you’re out of luck for displaying errors when your PHP scripts contain parse errors. You’d then have to resolve to linting the files on the command line like this:

find . -name '*.php' -type f -print0 | xargs -0 -n1 -P8 php -l | grep -v "No syntax errors"

If your host is so locked down that it does not allow changing the value via php.ini or .htaccess, it may also disallow changing the value via ini_set. You can check that with the following PHP script:

<?php
if( !ini_set( 'display_errors', 1 ) ) {
  echo "display_errors cannot be set.";
} else {
  echo "changing display_errors via script is possible.";
}

answered Jan 11, 2016 at 12:11

chiborg's user avatar

chiborgchiborg

26.1k12 gold badges98 silver badges114 bronze badges

1

You can do something like below:

Set the below parameters in your main index file:

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

Then based on your requirement you can choose which you want to show:

For all errors, warnings and notices:

    error_reporting(E_ALL); OR error_reporting(-1);

For all errors:

    error_reporting(E_ERROR);

For all warnings:

    error_reporting(E_WARNING);

For all notices:

    error_reporting(E_NOTICE);

For more information, check here.

Peter Mortensen's user avatar

answered Feb 1, 2017 at 7:33

Binit Ghetiya's user avatar

Binit GhetiyaBinit Ghetiya

1,8612 gold badges23 silver badges31 bronze badges

1

You can add your own custom error handler, which can provide extra debug information. Furthermore, you can set it up to send you the information via email.

function ERR_HANDLER($errno, $errstr, $errfile, $errline){
    $msg = "<b>Something bad happened.</b> [$errno] $errstr <br><br>
    <b>File:</b> $errfile <br>
    <b>Line:</b> $errline <br>
    <pre>".json_encode(debug_backtrace(), JSON_PRETTY_PRINT)."</pre> <br>";

    echo $msg;

    return false;
}

function EXC_HANDLER($exception){
    ERR_HANDLER(0, $exception->getMessage(), $exception->getFile(), $exception->getLine());
}

function shutDownFunction() {
    $error = error_get_last();
    if ($error["type"] == 1) {
        ERR_HANDLER($error["type"], $error["message"], $error["file"], $error["line"]);
    }
}

set_error_handler ("ERR_HANDLER", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
register_shutdown_function("shutdownFunction");
set_exception_handler("EXC_HANDLER");

Peter Mortensen's user avatar

answered Jun 4, 2017 at 14:41

lintabá's user avatar

lintabálintabá

7319 silver badges18 bronze badges

Accepted asnwer including extra options. In PHP files for in my DEVELOPMENT apache vhost (.htaccess if you can ensure it doesn’t get into production):

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

However, this doesn’t make PHP to show parse errors — the only way to show those errors is to modify your php.ini with this line:

display_errors = on

(if you don’t have access to php.ini, then putting this line in .htaccess might work too):

// I've added some extra options that set E_ALL as per https://www.php.net/manual/en/errorfunc.configuration.php.
php_flag log_errors on
php_flag display_errors on
php_flag display_startup_errors on
php_value error_reporting 2147483647
php_value error_log /var/www/mywebsite.ext/logs/php.error.log

answered Jan 8, 2022 at 22:17

webcoder.co.uk's user avatar

This code on top should work:

error_reporting(E_ALL);

However, try to edit the code on the phone in the file:

error_reporting =on

Peter Mortensen's user avatar

answered May 9, 2017 at 3:28

Joel Wembo's user avatar

Joel WemboJoel Wembo

8146 silver badges10 bronze badges

The best/easy/fast solution that you can use if it’s a quick debugging, is to surround your code with catching exceptions. That’s what I’m doing when I want to check something fast in production.

try {
    // Page code
}
catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "n";
}

Peter Mortensen's user avatar

answered Mar 27, 2017 at 2:31

Xakiru's user avatar

XakiruXakiru

2,4111 gold badge14 silver badges11 bronze badges

1

    <?php
    // Turn off error reporting
    error_reporting(0);

    // Report runtime errors
    error_reporting(E_ERROR | E_WARNING | E_PARSE);

    // Report all errors
    error_reporting(E_ALL);

    // Same as error_reporting(E_ALL);
    ini_set("error_reporting", E_ALL);

    // Report all errors except E_NOTICE
    error_reporting(E_ALL & ~E_NOTICE);
    ?>

While your site is live, the php.ini file should have display_errors disabled for security reasons. However, for the development environment, display_errors can be enabled for troubleshooting.

Lahiru Mirihagoda's user avatar

answered May 24, 2018 at 8:48

pardeep's user avatar

pardeeppardeep

3511 gold badge5 silver badges7 bronze badges

0

Just write:

error_reporting(-1);

answered Jan 13, 2017 at 18:56

jewelhuq's user avatar

jewelhuqjewelhuq

1,19214 silver badges19 bronze badges

0

You can do this by changing the php.ini file and add the following

display_errors = on
display_startup_errors = on

OR you can also use the following code as this always works for me

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

answered Apr 11, 2019 at 8:43

Muhammad Adeel Malik's user avatar

0

If you have Xdebug installed you can override every setting by setting:

xdebug.force_display_errors = 1;
xdebug.force_error_reporting = -1;

force_display_errors

Type: int, Default value: 0, Introduced in Xdebug >= 2.3 If this
setting is set to 1 then errors will always be displayed, no matter
what the setting of PHP’s display_errors is.

force_error_reporting

Type: int, Default value: 0, Introduced in Xdebug >= 2.3
This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set().

Peter Mortensen's user avatar

answered Oct 19, 2017 at 5:45

Peter Haberkorn's user avatar

You might want to use this code:

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

baduker's user avatar

baduker

17.2k9 gold badges31 silver badges51 bronze badges

answered Mar 28, 2019 at 12:42

Report all errors except E_NOTICE

error_reporting(E_ALL & ~E_NOTICE);

Display all PHP errors

error_reporting(E_ALL);  or ini_set('error_reporting', E_ALL);

Turn off all error reporting

error_reporting(0);

answered Dec 31, 2019 at 10:07

Shaikh Nadeem's user avatar

If it is on the command line, you can run php with -ddisplay_errors=1 to override the setting in php.ini:

php -ddisplay_errors=1 script.php

Peter Mortensen's user avatar

answered Oct 24, 2019 at 23:11

gvlasov's user avatar

gvlasovgvlasov

17.7k19 gold badges69 silver badges106 bronze badges

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

Put this at the top of your page.

answered Feb 28, 2021 at 0:51

Kwed's user avatar

KwedKwed

2313 silver badges4 bronze badges

Input this on the top of your code

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

And in the php.ini file, insert this:

display_errors = on

This must work.

answered Aug 23, 2021 at 21:22

ropehapi's user avatar

You can show Php error in your display via simple ways.
Firstly, just put this below code in your php.ini file.

display_errors = on;

(if you don’t have access to php.ini, then putting this line in .htaccess might work too):

php_flag display_errors 1

OR you can also use the following code in your index.php file

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

answered Nov 6, 2020 at 6:41

Devsaiful's user avatar

In Unix CLI, it’s very practical to redirect only errors to a file:

./script 2> errors.log

From your script, either use var_dump() or equivalent as usual (both STDOUT and STDERR will receive the output), but to write only in the log file:

fwrite(STDERR, "Debug infosn"); // Write in errors.log^

Then from another shell, for live changes:

tail -f errors.log

or simply

watch cat errors.log

answered Nov 26, 2019 at 2:28

NVRM's user avatar

NVRMNVRM

10.5k1 gold badge82 silver badges85 bronze badges

2

This always works for me:

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

However, this doesn’t make PHP to show parse errors — the only way to show those errors is to modify your php.ini with this line:

display_errors = on

(if you don’t have access to php.ini, then putting this line in .htaccess might work too):

php_flag display_errors 1

anthonyryan1's user avatar

anthonyryan1

4,6472 gold badges33 silver badges27 bronze badges

answered Jan 29, 2014 at 11:25

Fancy John's user avatar

Fancy JohnFancy John

37.4k3 gold badges26 silver badges25 bronze badges

16

You can’t catch parse errors when enabling error output at runtime, because it parses the file before actually executing anything (and since it encounters an error during this, it won’t execute anything). You’ll need to change the actual server configuration so that display_errors is on and the approriate error_reporting level is used. If you don’t have access to php.ini, you may be able to use .htaccess or similar, depending on the server.

This question may provide additional info.

Community's user avatar

answered Jun 27, 2009 at 19:14

Michael Madsen's user avatar

Michael MadsenMichael Madsen

53.8k7 gold badges72 silver badges83 bronze badges

0

Inside your php.ini:

display_errors = on

Then restart your web server.

j0k's user avatar

j0k

22.4k28 gold badges80 silver badges88 bronze badges

answered Jan 8, 2013 at 9:27

user1803477's user avatar

user1803477user1803477

1,5951 gold badge9 silver badges4 bronze badges

5

To display all errors you need to:

1. Have these lines in the PHP script you’re calling from the browser (typically index.php):

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

2.(a) Make sure that this script has no syntax errors

—or—

2.(b) Set display_errors = On in your php.ini

Otherwise, it can’t even run those 2 lines!

You can check for syntax errors in your script by running (at the command line):

php -l index.php

If you include the script from another PHP script then it will display syntax errors in the included script. For example:

index.php

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

// Any syntax errors here will result in a blank screen in the browser

include 'my_script.php';

my_script.php

adjfkj // This syntax error will be displayed in the browser

answered Jan 29, 2014 at 9:52

andre's user avatar

andreandre

1,8311 gold badge16 silver badges8 bronze badges

2

Some web hosting providers allow you to change PHP parameters in the .htaccess file.

You can add the following line:

php_value display_errors 1

I had the same issue as yours and this solution fixed it.

Peter Mortensen's user avatar

answered May 18, 2013 at 15:01

Kalhua's user avatar

KalhuaKalhua

5614 silver badges2 bronze badges

1

You might find all of the settings for «error reporting» or «display errors» do not appear to work in PHP 7. That is because error handling has changed. Try this instead:

try{
     // Your code
} 
catch(Error $e) {
    $trace = $e->getTrace();
    echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}

Or, to catch exceptions and errors in one go (this is not backward compatible with PHP 5):

try{
     // Your code
} 
catch(Throwable $e) {
    $trace = $e->getTrace();
    echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}

answered Mar 28, 2016 at 19:26

Frank Forte's user avatar

Frank ForteFrank Forte

1,89718 silver badges18 bronze badges

9

This will work:

<?php
     error_reporting(E_ALL);
     ini_set('display_errors', 1);    
?>

Peter Mortensen's user avatar

answered May 5, 2014 at 13:23

Mahendra Jella's user avatar

Mahendra JellaMahendra Jella

5,2801 gold badge32 silver badges38 bronze badges

1

Use:

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

This is the best way to write it, but a syntax error gives blank output, so use the console to check for syntax errors. The best way to debug PHP code is to use the console; run the following:

php -l phpfilename.php

Peter Mortensen's user avatar

answered May 4, 2016 at 19:14

Abhijit Jagtap's user avatar

Abhijit JagtapAbhijit Jagtap

2,6852 gold badges32 silver badges43 bronze badges

0

Set this in your index.php file:

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

Peter Mortensen's user avatar

answered Sep 26, 2017 at 12:32

Sumit Gupta's user avatar

Sumit GuptaSumit Gupta

5694 silver badges12 bronze badges

0

Create a file called php.ini in the folder where your PHP file resides.

Inside php.ini add the following code (I am giving an simple error showing code):

display_errors = on

display_startup_errors = on

Peter Mortensen's user avatar

answered Mar 31, 2015 at 18:38

NavyaKumar's user avatar

NavyaKumarNavyaKumar

5895 silver badges3 bronze badges

As we are now running PHP 7, answers given here are not correct any more. The only one still OK is the one from Frank Forte, as he talks about PHP 7.

On the other side, rather than trying to catch errors with a try/catch you can use a trick: use include.

Here three pieces of code:

File: tst1.php

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 'On');
    // Missing " and ;
    echo "Testing
?>

Running this in PHP 7 will show nothing.

Now, try this:

File: tst2.php

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 'On');
    include ("tst3.php");
?>

File: tst3.php

<?php
    // Missing " and ;
    echo "Testing
?>

Now run tst2 which sets the error reporting, and then include tst3. You will see:

Parse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in tst3.php on line 4

Peter Mortensen's user avatar

answered May 20, 2017 at 12:07

Peter's user avatar

PeterPeter

1,23318 silver badges32 bronze badges

2

I would usually go with the following code in my plain PHP projects.

if(!defined('ENVIRONMENT')){
    define('ENVIRONMENT', 'DEVELOPMENT');
}

$base_url = null;

if (defined('ENVIRONMENT'))
{
    switch (ENVIRONMENT)
    {
        case 'DEVELOPMENT':
            $base_url = 'http://localhost/product/';
            ini_set('display_errors', 1);
            ini_set('display_startup_errors', 1);
            error_reporting(E_ALL|E_STRICT);
            break;

        case 'PRODUCTION':
            $base_url = 'Production URL'; /* https://google.com */
            error_reporting(0);
            /* Mechanism to log errors */
            break;

        default:
            exit('The application environment is not set correctly.');
    }
}

answered Feb 1, 2017 at 7:16

Channaveer Hakari's user avatar

If, despite following all of the above answers (or you can’t edit your php.ini file), you still can’t get an error message, try making a new PHP file that enables error reporting and then include the problem file. eg:

error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('problem_file.php');

Despite having everything set properly in my php.ini file, this was the only way I could catch a namespace error. My exact scenario was:

//file1.php
namespace ab;
class x {
    ...
}

//file2.php
namespace cd;
use cdx; //Dies because it's not sure which 'x' class to use
class x {
    ...
}

answered Apr 24, 2015 at 2:55

jxmallett's user avatar

jxmallettjxmallett

4,0471 gold badge28 silver badges35 bronze badges

2

If you somehow find yourself in a situation where you can’t modifiy the setting via php.ini or .htaccess you’re out of luck for displaying errors when your PHP scripts contain parse errors. You’d then have to resolve to linting the files on the command line like this:

find . -name '*.php' -type f -print0 | xargs -0 -n1 -P8 php -l | grep -v "No syntax errors"

If your host is so locked down that it does not allow changing the value via php.ini or .htaccess, it may also disallow changing the value via ini_set. You can check that with the following PHP script:

<?php
if( !ini_set( 'display_errors', 1 ) ) {
  echo "display_errors cannot be set.";
} else {
  echo "changing display_errors via script is possible.";
}

answered Jan 11, 2016 at 12:11

chiborg's user avatar

chiborgchiborg

26.1k12 gold badges98 silver badges114 bronze badges

1

You can do something like below:

Set the below parameters in your main index file:

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

Then based on your requirement you can choose which you want to show:

For all errors, warnings and notices:

    error_reporting(E_ALL); OR error_reporting(-1);

For all errors:

    error_reporting(E_ERROR);

For all warnings:

    error_reporting(E_WARNING);

For all notices:

    error_reporting(E_NOTICE);

For more information, check here.

Peter Mortensen's user avatar

answered Feb 1, 2017 at 7:33

Binit Ghetiya's user avatar

Binit GhetiyaBinit Ghetiya

1,8612 gold badges23 silver badges31 bronze badges

1

You can add your own custom error handler, which can provide extra debug information. Furthermore, you can set it up to send you the information via email.

function ERR_HANDLER($errno, $errstr, $errfile, $errline){
    $msg = "<b>Something bad happened.</b> [$errno] $errstr <br><br>
    <b>File:</b> $errfile <br>
    <b>Line:</b> $errline <br>
    <pre>".json_encode(debug_backtrace(), JSON_PRETTY_PRINT)."</pre> <br>";

    echo $msg;

    return false;
}

function EXC_HANDLER($exception){
    ERR_HANDLER(0, $exception->getMessage(), $exception->getFile(), $exception->getLine());
}

function shutDownFunction() {
    $error = error_get_last();
    if ($error["type"] == 1) {
        ERR_HANDLER($error["type"], $error["message"], $error["file"], $error["line"]);
    }
}

set_error_handler ("ERR_HANDLER", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
register_shutdown_function("shutdownFunction");
set_exception_handler("EXC_HANDLER");

Peter Mortensen's user avatar

answered Jun 4, 2017 at 14:41

lintabá's user avatar

lintabálintabá

7319 silver badges18 bronze badges

Accepted asnwer including extra options. In PHP files for in my DEVELOPMENT apache vhost (.htaccess if you can ensure it doesn’t get into production):

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

However, this doesn’t make PHP to show parse errors — the only way to show those errors is to modify your php.ini with this line:

display_errors = on

(if you don’t have access to php.ini, then putting this line in .htaccess might work too):

// I've added some extra options that set E_ALL as per https://www.php.net/manual/en/errorfunc.configuration.php.
php_flag log_errors on
php_flag display_errors on
php_flag display_startup_errors on
php_value error_reporting 2147483647
php_value error_log /var/www/mywebsite.ext/logs/php.error.log

answered Jan 8, 2022 at 22:17

webcoder.co.uk's user avatar

This code on top should work:

error_reporting(E_ALL);

However, try to edit the code on the phone in the file:

error_reporting =on

Peter Mortensen's user avatar

answered May 9, 2017 at 3:28

Joel Wembo's user avatar

Joel WemboJoel Wembo

8146 silver badges10 bronze badges

The best/easy/fast solution that you can use if it’s a quick debugging, is to surround your code with catching exceptions. That’s what I’m doing when I want to check something fast in production.

try {
    // Page code
}
catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "n";
}

Peter Mortensen's user avatar

answered Mar 27, 2017 at 2:31

Xakiru's user avatar

XakiruXakiru

2,4111 gold badge14 silver badges11 bronze badges

1

    <?php
    // Turn off error reporting
    error_reporting(0);

    // Report runtime errors
    error_reporting(E_ERROR | E_WARNING | E_PARSE);

    // Report all errors
    error_reporting(E_ALL);

    // Same as error_reporting(E_ALL);
    ini_set("error_reporting", E_ALL);

    // Report all errors except E_NOTICE
    error_reporting(E_ALL & ~E_NOTICE);
    ?>

While your site is live, the php.ini file should have display_errors disabled for security reasons. However, for the development environment, display_errors can be enabled for troubleshooting.

Lahiru Mirihagoda's user avatar

answered May 24, 2018 at 8:48

pardeep's user avatar

pardeeppardeep

3511 gold badge5 silver badges7 bronze badges

0

Just write:

error_reporting(-1);

answered Jan 13, 2017 at 18:56

jewelhuq's user avatar

jewelhuqjewelhuq

1,19214 silver badges19 bronze badges

0

You can do this by changing the php.ini file and add the following

display_errors = on
display_startup_errors = on

OR you can also use the following code as this always works for me

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

answered Apr 11, 2019 at 8:43

Muhammad Adeel Malik's user avatar

0

If you have Xdebug installed you can override every setting by setting:

xdebug.force_display_errors = 1;
xdebug.force_error_reporting = -1;

force_display_errors

Type: int, Default value: 0, Introduced in Xdebug >= 2.3 If this
setting is set to 1 then errors will always be displayed, no matter
what the setting of PHP’s display_errors is.

force_error_reporting

Type: int, Default value: 0, Introduced in Xdebug >= 2.3
This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set().

Peter Mortensen's user avatar

answered Oct 19, 2017 at 5:45

Peter Haberkorn's user avatar

You might want to use this code:

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

baduker's user avatar

baduker

17.2k9 gold badges31 silver badges51 bronze badges

answered Mar 28, 2019 at 12:42

Report all errors except E_NOTICE

error_reporting(E_ALL & ~E_NOTICE);

Display all PHP errors

error_reporting(E_ALL);  or ini_set('error_reporting', E_ALL);

Turn off all error reporting

error_reporting(0);

answered Dec 31, 2019 at 10:07

Shaikh Nadeem's user avatar

If it is on the command line, you can run php with -ddisplay_errors=1 to override the setting in php.ini:

php -ddisplay_errors=1 script.php

Peter Mortensen's user avatar

answered Oct 24, 2019 at 23:11

gvlasov's user avatar

gvlasovgvlasov

17.7k19 gold badges69 silver badges106 bronze badges

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

Put this at the top of your page.

answered Feb 28, 2021 at 0:51

Kwed's user avatar

KwedKwed

2313 silver badges4 bronze badges

Input this on the top of your code

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

And in the php.ini file, insert this:

display_errors = on

This must work.

answered Aug 23, 2021 at 21:22

ropehapi's user avatar

You can show Php error in your display via simple ways.
Firstly, just put this below code in your php.ini file.

display_errors = on;

(if you don’t have access to php.ini, then putting this line in .htaccess might work too):

php_flag display_errors 1

OR you can also use the following code in your index.php file

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

answered Nov 6, 2020 at 6:41

Devsaiful's user avatar

In Unix CLI, it’s very practical to redirect only errors to a file:

./script 2> errors.log

From your script, either use var_dump() or equivalent as usual (both STDOUT and STDERR will receive the output), but to write only in the log file:

fwrite(STDERR, "Debug infosn"); // Write in errors.log^

Then from another shell, for live changes:

tail -f errors.log

or simply

watch cat errors.log

answered Nov 26, 2019 at 2:28

NVRM's user avatar

NVRMNVRM

10.5k1 gold badge82 silver badges85 bronze badges

2

Directives

Syntax: absolute_redirect on | off;
Default:
absolute_redirect on;
Context: http, server, location

This directive appeared in version 1.11.8.

If disabled, redirects issued by nginx will be relative.

See also server_name_in_redirect
and port_in_redirect directives.

Syntax: aio
on |
off |
threads[=pool];
Default:
aio off;
Context: http, server, location

This directive appeared in version 0.8.11.

Enables or disables the use of asynchronous file I/O (AIO)
on FreeBSD and Linux:

location /video/ {
    aio            on;
    output_buffers 1 64k;
}

On FreeBSD, AIO can be used starting from FreeBSD 4.3.
Prior to FreeBSD 11.0,
AIO can either be linked statically into a kernel:

options VFS_AIO

or loaded dynamically as a kernel loadable module:

kldload aio

On Linux, AIO can be used starting from kernel version 2.6.22.
Also, it is necessary to enable
directio,
or otherwise reading will be blocking:

location /video/ {
    aio            on;
    directio       512;
    output_buffers 1 128k;
}

On Linux,
directio
can only be used for reading blocks that are aligned on 512-byte
boundaries (or 4K for XFS).
File’s unaligned end is read in blocking mode.
The same holds true for byte range requests and for FLV requests
not from the beginning of a file: reading of unaligned data at the
beginning and end of a file will be blocking.

When both AIO and sendfile are enabled on Linux,
AIO is used for files that are larger than or equal to
the size specified in the directio directive,
while sendfile is used for files of smaller sizes
or when directio is disabled.

location /video/ {
    sendfile       on;
    aio            on;
    directio       8m;
}

Finally, files can be read and sent
using multi-threading (1.7.11),
without blocking a worker process:

location /video/ {
    sendfile       on;
    aio            threads;
}

Read and send file operations are offloaded to threads of the specified
pool.
If the pool name is omitted,
the pool with the name “default” is used.
The pool name can also be set with variables:

aio threads=pool$disk;

By default, multi-threading is disabled, it should be
enabled with the
--with-threads configuration parameter.
Currently, multi-threading is compatible only with the
epoll,
kqueue,
and
eventport methods.
Multi-threaded sending of files is only supported on Linux.

See also the sendfile directive.

Syntax: aio_write on | off;
Default:
aio_write off;
Context: http, server, location

This directive appeared in version 1.9.13.

If aio is enabled, specifies whether it is used for writing files.
Currently, this only works when using
aio threads
and is limited to writing temporary files
with data received from proxied servers.

Syntax: alias path;
Default:

Context: location

Defines a replacement for the specified location.
For example, with the following configuration

location /i/ {
    alias /data/w3/images/;
}

on request of
/i/top.gif”, the file
/data/w3/images/top.gif will be sent.

The path value can contain variables,
except $document_root and $realpath_root.

If alias is used inside a location defined
with a regular expression then such regular expression should
contain captures and alias should refer to
these captures (0.7.40), for example:

location ~ ^/users/(.+.(?:gif|jpe?g|png))$ {
    alias /data/w3/images/$1;
}

When location matches the last part of the directive’s value:

location /images/ {
    alias /data/w3/images/;
}

it is better to use the
root
directive instead:

location /images/ {
    root /data/w3;
}
Syntax: auth_delay time;
Default:
auth_delay 0s;
Context: http, server, location

This directive appeared in version 1.17.10.

Delays processing of unauthorized requests with 401 response code
to prevent timing attacks when access is limited by
password, by the
result of subrequest,
or by JWT.

Syntax: chunked_transfer_encoding on | off;
Default:
chunked_transfer_encoding on;
Context: http, server, location

Allows disabling chunked transfer encoding in HTTP/1.1.
It may come in handy when using a software failing to support
chunked encoding despite the standard’s requirement.

Syntax: client_body_buffer_size size;
Default:
client_body_buffer_size 8k|16k;
Context: http, server, location

Sets buffer size for reading client request body.
In case the request body is larger than the buffer,
the whole body or only its part is written to a
temporary file.
By default, buffer size is equal to two memory pages.
This is 8K on x86, other 32-bit platforms, and x86-64.
It is usually 16K on other 64-bit platforms.

Syntax: client_body_in_file_only
on |
clean |
off;
Default:
client_body_in_file_only off;
Context: http, server, location

Determines whether nginx should save the entire client request body
into a file.
This directive can be used during debugging, or when using the
$request_body_file
variable, or the
$r->request_body_file
method of the module
ngx_http_perl_module.

When set to the value on, temporary files are not
removed after request processing.

The value clean will cause the temporary files
left after request processing to be removed.

Syntax: client_body_in_single_buffer on | off;
Default:
client_body_in_single_buffer off;
Context: http, server, location

Determines whether nginx should save the entire client request body
in a single buffer.
The directive is recommended when using the
$request_body
variable, to save the number of copy operations involved.

Syntax: client_body_temp_path
path
[level1
[level2
[level3]]];
Default:
client_body_temp_path client_body_temp;
Context: http, server, location

Defines a directory for storing temporary files holding client request bodies.
Up to three-level subdirectory hierarchy can be used under the specified
directory.
For example, in the following configuration

client_body_temp_path /spool/nginx/client_temp 1 2;

a path to a temporary file might look like this:

/spool/nginx/client_temp/7/45/00000123457
Syntax: client_body_timeout time;
Default:
client_body_timeout 60s;
Context: http, server, location

Defines a timeout for reading client request body.
The timeout is set only for a period between two successive read operations,
not for the transmission of the whole request body.
If a client does not transmit anything within this time, the
request is terminated with the
408 (Request Time-out)
error.

Syntax: client_header_buffer_size size;
Default:
client_header_buffer_size 1k;
Context: http, server

Sets buffer size for reading client request header.
For most requests, a buffer of 1K bytes is enough.
However, if a request includes long cookies, or comes from a WAP client,
it may not fit into 1K.
If a request line or a request header field does not fit into
this buffer then larger buffers, configured by the
large_client_header_buffers directive,
are allocated.

If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.

Syntax: client_header_timeout time;
Default:
client_header_timeout 60s;
Context: http, server

Defines a timeout for reading client request header.
If a client does not transmit the entire header within this time, the
request is terminated with the
408 (Request Time-out)
error.

Syntax: client_max_body_size size;
Default:
client_max_body_size 1m;
Context: http, server, location

Sets the maximum allowed size of the client request body.
If the size in a request exceeds the configured value, the
413 (Request Entity Too Large)
error is returned to the client.
Please be aware that
browsers cannot correctly display
this error.
Setting size to 0 disables checking of client
request body size.

Syntax: connection_pool_size size;
Default:
connection_pool_size 256|512;
Context: http, server

Allows accurate tuning of per-connection memory allocations.
This directive has minimal impact on performance
and should not generally be used.
By default, the size is equal to
256 bytes on 32-bit platforms and 512 bytes on 64-bit platforms.

Prior to version 1.9.8, the default value was 256 on all platforms.

Syntax: default_type mime-type;
Default:
default_type text/plain;
Context: http, server, location

Defines the default MIME type of a response.
Mapping of file name extensions to MIME types can be set
with the types directive.

Syntax: directio size | off;
Default:
directio off;
Context: http, server, location

This directive appeared in version 0.7.7.

Enables the use of
the O_DIRECT flag (FreeBSD, Linux),
the F_NOCACHE flag (macOS),
or the directio() function (Solaris),
when reading files that are larger than or equal to
the specified size.
The directive automatically disables (0.7.15) the use of
sendfile
for a given request.
It can be useful for serving large files:

directio 4m;

or when using aio on Linux.

Syntax: directio_alignment size;
Default:
directio_alignment 512;
Context: http, server, location

This directive appeared in version 0.8.11.

Sets the alignment for
directio.
In most cases, a 512-byte alignment is enough.
However, when using XFS under Linux, it needs to be increased to 4K.

Syntax: disable_symlinks off;
disable_symlinks
on |
if_not_owner
[from=part];
Default:
disable_symlinks off;
Context: http, server, location

This directive appeared in version 1.1.15.

Determines how symbolic links should be treated when opening files:

off
Symbolic links in the pathname are allowed and not checked.
This is the default behavior.
on
If any component of the pathname is a symbolic link,
access to a file is denied.
if_not_owner
Access to a file is denied if any component of the pathname
is a symbolic link, and the link and object that the link
points to have different owners.
from=part
When checking symbolic links
(parameters on and if_not_owner),
all components of the pathname are normally checked.
Checking of symbolic links in the initial part of the pathname
may be avoided by specifying additionally the
from=part parameter.
In this case, symbolic links are checked only from
the pathname component that follows the specified initial part.
If the value is not an initial part of the pathname checked, the whole
pathname is checked as if this parameter was not specified at all.
If the value matches the whole file name,
symbolic links are not checked.
The parameter value can contain variables.

Example:

disable_symlinks on from=$document_root;

This directive is only available on systems that have the
openat() and fstatat() interfaces.
Such systems include modern versions of FreeBSD, Linux, and Solaris.

Parameters on and if_not_owner
add a processing overhead.

On systems that do not support opening of directories only for search,
to use these parameters it is required that worker processes
have read permissions for all directories being checked.

The
ngx_http_autoindex_module,
ngx_http_random_index_module,
and ngx_http_dav_module
modules currently ignore this directive.

Syntax: error_page
code ...
[=[response]]
uri;
Default:

Context: http, server, location, if in location

Defines the URI that will be shown for the specified errors.
A uri value can contain variables.

Example:

error_page 404             /404.html;
error_page 500 502 503 504 /50x.html;

This causes an internal redirect to the specified uri
with the client request method changed to “GET
(for all methods other than
GET” and “HEAD”).

Furthermore, it is possible to change the response code to another
using the “=response” syntax, for example:

error_page 404 =200 /empty.gif;

If an error response is processed by a proxied server
or a FastCGI/uwsgi/SCGI/gRPC server,
and the server may return different response codes (e.g., 200, 302, 401
or 404), it is possible to respond with the code it returns:

error_page 404 = /404.php;

If there is no need to change URI and method during internal redirection
it is possible to pass error processing into a named location:

location / {
    error_page 404 = @fallback;
}

location @fallback {
    proxy_pass http://backend;
}

If uri processing leads to an error,
the status code of the last occurred error is returned to the client.

It is also possible to use URL redirects for error processing:

error_page 403      http://example.com/forbidden.html;
error_page 404 =301 http://example.com/notfound.html;

In this case, by default, the response code 302 is returned to the client.
It can only be changed to one of the redirect status
codes (301, 302, 303, 307, and 308).

The code 307 was not treated as a redirect until versions 1.1.16 and 1.0.13.

The code 308 was not treated as a redirect until version 1.13.0.

These directives are inherited from the previous configuration level
if and only if there are no error_page directives
defined on the current level.

Syntax: etag on | off;
Default:
etag on;
Context: http, server, location

This directive appeared in version 1.3.3.

Enables or disables automatic generation of the “ETag”
response header field for static resources.

Syntax: http { ... }
Default:

Context: main

Provides the configuration file context in which the HTTP server directives
are specified.

Syntax: if_modified_since
off |
exact |
before;
Default:
if_modified_since exact;
Context: http, server, location

This directive appeared in version 0.7.24.

Specifies how to compare modification time of a response
with the time in the
“If-Modified-Since”
request header field:

off
the response is always considered modified (0.7.34);
exact
exact match;
before
modification time of the response is
less than or equal to the time in the “If-Modified-Since”
request header field.
Syntax: ignore_invalid_headers on | off;
Default:
ignore_invalid_headers on;
Context: http, server

Controls whether header fields with invalid names should be ignored.
Valid names are composed of English letters, digits, hyphens, and possibly
underscores (as controlled by the underscores_in_headers
directive).

If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.

Syntax: internal;
Default:

Context: location

Specifies that a given location can only be used for internal requests.
For external requests, the client error
404 (Not Found)
is returned.
Internal requests are the following:

  • requests redirected by the
    error_page,
    index,
    random_index, and
    try_files directives;
  • requests redirected by the “X-Accel-Redirect”
    response header field from an upstream server;
  • subrequests formed by the
    include virtual
    command of the
    ngx_http_ssi_module
    module, by the
    ngx_http_addition_module
    module directives, and by
    auth_request and
    mirror directives;
  • requests changed by the
    rewrite directive.

Example:

error_page 404 /404.html;

location = /404.html {
    internal;
}

There is a limit of 10 internal redirects per request to prevent
request processing cycles that can occur in incorrect configurations.
If this limit is reached, the error
500 (Internal Server Error) is returned.
In such cases, the “rewrite or internal redirection cycle” message
can be seen in the error log.

Syntax: keepalive_disable none | browser ...;
Default:
keepalive_disable msie6;
Context: http, server, location

Disables keep-alive connections with misbehaving browsers.
The browser parameters specify which
browsers will be affected.
The value msie6 disables keep-alive connections
with old versions of MSIE, once a POST request is received.
The value safari disables keep-alive connections
with Safari and Safari-like browsers on macOS and macOS-like
operating systems.
The value none enables keep-alive connections
with all browsers.

Prior to version 1.1.18, the value safari matched
all Safari and Safari-like browsers on all operating systems, and
keep-alive connections with them were disabled by default.

Syntax: keepalive_requests number;
Default:
keepalive_requests 1000;
Context: http, server, location

This directive appeared in version 0.8.0.

Sets the maximum number of requests that can be
served through one keep-alive connection.
After the maximum number of requests are made, the connection is closed.

Closing connections periodically is necessary to free
per-connection memory allocations.
Therefore, using too high maximum number of requests
could result in excessive memory usage and not recommended.

Prior to version 1.19.10, the default value was 100.

Syntax: keepalive_time time;
Default:
keepalive_time 1h;
Context: http, server, location

This directive appeared in version 1.19.10.

Limits the maximum time during which
requests can be processed through one keep-alive connection.
After this time is reached, the connection is closed
following the subsequent request processing.

Syntax: keepalive_timeout
timeout
[header_timeout];
Default:
keepalive_timeout 75s;
Context: http, server, location

The first parameter sets a timeout during which a keep-alive
client connection will stay open on the server side.
The zero value disables keep-alive client connections.
The optional second parameter sets a value in the
“Keep-Alive: timeout=time
response header field.
Two parameters may differ.

The
“Keep-Alive: timeout=time
header field is recognized by Mozilla and Konqueror.
MSIE closes keep-alive connections by itself in about 60 seconds.

Syntax: large_client_header_buffers number size;
Default:
large_client_header_buffers 4 8k;
Context: http, server

Sets the maximum number and size of
buffers used for reading large client request header.
A request line cannot exceed the size of one buffer, or the
414 (Request-URI Too Large)
error is returned to the client.
A request header field cannot exceed the size of one buffer as well, or the
400 (Bad Request)
error is returned to the client.
Buffers are allocated only on demand.
By default, the buffer size is equal to 8K bytes.
If after the end of request processing a connection is transitioned
into the keep-alive state, these buffers are released.

If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.

Syntax: limit_except method ... { ... }
Default:

Context: location

Limits allowed HTTP methods inside a location.
The method parameter can be one of the following:
GET,
HEAD,
POST,
PUT,
DELETE,
MKCOL,
COPY,
MOVE,
OPTIONS,
PROPFIND,
PROPPATCH,
LOCK,
UNLOCK,
or
PATCH.
Allowing the GET method makes the
HEAD method also allowed.
Access to other methods can be limited using the
ngx_http_access_module,
ngx_http_auth_basic_module,
and
ngx_http_auth_jwt_module
(1.13.10)
modules directives:

limit_except GET {
    allow 192.168.1.0/32;
    deny  all;
}

Please note that this will limit access to all methods
except GET and HEAD.

Syntax: limit_rate rate;
Default:
limit_rate 0;
Context: http, server, location, if in location

Limits the rate of response transmission to a client.
The rate is specified in bytes per second.
The zero value disables rate limiting.

The limit is set per a request, and so if a client simultaneously opens
two connections, the overall rate will be twice as much
as the specified limit.

Parameter value can contain variables (1.17.0).
It may be useful in cases where rate should be limited
depending on a certain condition:

map $slow $rate {
    1     4k;
    2     8k;
}

limit_rate $rate;

Rate limit can also be set in the
$limit_rate variable,
however, since version 1.17.0, this method is not recommended:

server {

    if ($slow) {
        set $limit_rate 4k;
    }

    ...
}

Rate limit can also be set in the
“X-Accel-Limit-Rate” header field of a proxied server response.
This capability can be disabled using the
proxy_ignore_headers,
fastcgi_ignore_headers,
uwsgi_ignore_headers,
and
scgi_ignore_headers
directives.

Syntax: limit_rate_after size;
Default:
limit_rate_after 0;
Context: http, server, location, if in location

This directive appeared in version 0.8.0.

Sets the initial amount after which the further transmission
of a response to a client will be rate limited.
Parameter value can contain variables (1.17.0).

Example:

location /flv/ {
    flv;
    limit_rate_after 500k;
    limit_rate       50k;
}
Syntax: lingering_close
off |
on |
always;
Default:
lingering_close on;
Context: http, server, location

This directive appeared in versions 1.1.0 and 1.0.6.

Controls how nginx closes client connections.

The default value “on” instructs nginx to
wait for and
process additional data from a client
before fully closing a connection, but only
if heuristics suggests that a client may be sending more data.

The value “always” will cause nginx to unconditionally
wait for and process additional client data.

The value “off” tells nginx to never wait for
more data and close the connection immediately.
This behavior breaks the protocol and should not be used under normal
circumstances.

To control closing
HTTP/2 connections,
the directive must be specified on the server level (1.19.1).

Syntax: lingering_time time;
Default:
lingering_time 30s;
Context: http, server, location

When lingering_close is in effect,
this directive specifies the maximum time during which nginx
will process (read and ignore) additional data coming from a client.
After that, the connection will be closed, even if there will be
more data.

Syntax: lingering_timeout time;
Default:
lingering_timeout 5s;
Context: http, server, location

When lingering_close is in effect, this directive specifies
the maximum waiting time for more client data to arrive.
If data are not received during this time, the connection is closed.
Otherwise, the data are read and ignored, and nginx starts waiting
for more data again.
The “wait-read-ignore” cycle is repeated, but no longer than specified by the
lingering_time directive.

Syntax: listen
address[:port]
[default_server]
[ssl]
[http2 | spdy]
[proxy_protocol]
[setfib=number]
[fastopen=number]
[backlog=number]
[rcvbuf=size]
[sndbuf=size]
[accept_filter=filter]
[deferred]
[bind]
[ipv6only=on|off]
[reuseport]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

listen
port
[default_server]
[ssl]
[http2 | spdy]
[proxy_protocol]
[setfib=number]
[fastopen=number]
[backlog=number]
[rcvbuf=size]
[sndbuf=size]
[accept_filter=filter]
[deferred]
[bind]
[ipv6only=on|off]
[reuseport]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

listen
unix:path
[default_server]
[ssl]
[http2 | spdy]
[proxy_protocol]
[backlog=number]
[rcvbuf=size]
[sndbuf=size]
[accept_filter=filter]
[deferred]
[bind]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
Default:
listen *:80 | *:8000;
Context: server

Sets the address and port for IP,
or the path for a UNIX-domain socket on which
the server will accept requests.
Both address and port,
or only address or only port can be specified.
An address may also be a hostname, for example:

listen 127.0.0.1:8000;
listen 127.0.0.1;
listen 8000;
listen *:8000;
listen localhost:8000;

IPv6 addresses (0.7.36) are specified in square brackets:

listen [::]:8000;
listen [::1];

UNIX-domain sockets (0.8.21) are specified with the “unix:
prefix:

listen unix:/var/run/nginx.sock;

If only address is given, the port 80 is used.

If the directive is not present then either *:80 is used
if nginx runs with the superuser privileges, or *:8000
otherwise.

The default_server parameter, if present,
will cause the server to become the default server for the specified
address:port pair.
If none of the directives have the default_server
parameter then the first server with the
address:port pair will be
the default server for this pair.

In versions prior to 0.8.21 this parameter is named simply
default.

The ssl parameter (0.7.14) allows specifying that all
connections accepted on this port should work in SSL mode.
This allows for a more compact configuration for the server that
handles both HTTP and HTTPS requests.

The http2 parameter (1.9.5) configures the port to accept
HTTP/2 connections.
Normally, for this to work the ssl parameter should be
specified as well, but nginx can also be configured to accept HTTP/2
connections without SSL.

The spdy parameter (1.3.15-1.9.4) allows accepting
SPDY connections on this port.
Normally, for this to work the ssl parameter should be
specified as well, but nginx can also be configured to accept SPDY
connections without SSL.

The proxy_protocol parameter (1.5.12)
allows specifying that all connections accepted on this port should use the
PROXY
protocol.

The PROXY protocol version 2 is supported since version 1.13.11.

The listen directive
can have several additional parameters specific to socket-related system calls.
These parameters can be specified in any
listen directive, but only once for a given
address:port pair.

In versions prior to 0.8.21, they could only be
specified in the listen directive together with the
default parameter.

setfib=number
this parameter (0.8.44) sets the associated routing table, FIB
(the SO_SETFIB option) for the listening socket.
This currently works only on FreeBSD.
fastopen=number
enables
“TCP Fast Open”
for the listening socket (1.5.8) and
limits
the maximum length for the queue of connections that have not yet completed
the three-way handshake.

Do not enable this feature unless the server can handle
receiving the

same SYN packet with data more than once.

backlog=number
sets the backlog parameter in the
listen() call that limits
the maximum length for the queue of pending connections.
By default,
backlog is set to -1 on FreeBSD, DragonFly BSD, and macOS,
and to 511 on other platforms.
rcvbuf=size
sets the receive buffer size
(the SO_RCVBUF option) for the listening socket.
sndbuf=size
sets the send buffer size
(the SO_SNDBUF option) for the listening socket.
accept_filter=filter
sets the name of accept filter
(the SO_ACCEPTFILTER option) for the listening socket
that filters incoming connections before passing them to
accept().
This works only on FreeBSD and NetBSD 5.0+.
Possible values are
dataready
and
httpready.
deferred
instructs to use a deferred accept()
(the TCP_DEFER_ACCEPT socket option) on Linux.
bind
instructs to make a separate bind() call for a given
address:port pair.
This is useful because if there are several listen
directives with the same port but different addresses, and one of the
listen directives listens on all addresses
for the given port (*:port), nginx
will bind() only to *:port.
It should be noted that the getsockname() system call will be
made in this case to determine the address that accepted the connection.
If the setfib,
fastopen,
backlog, rcvbuf,
sndbuf, accept_filter,
deferred, ipv6only,
reuseport,
or so_keepalive parameters
are used then for a given
address:port pair
a separate bind() call will always be made.
ipv6only=on|off
this parameter (0.7.42) determines
(via the IPV6_V6ONLY socket option)
whether an IPv6 socket listening on a wildcard address [::]
will accept only IPv6 connections or both IPv6 and IPv4 connections.
This parameter is turned on by default.
It can only be set once on start.

Prior to version 1.3.4,
if this parameter was omitted then the operating system’s settings were
in effect for the socket.

reuseport
this parameter (1.9.1) instructs to create an individual listening socket
for each worker process
(using the
SO_REUSEPORT socket option on Linux 3.9+ and DragonFly BSD,
or SO_REUSEPORT_LB on FreeBSD 12+), allowing a kernel
to distribute incoming connections between worker processes.
This currently works only on Linux 3.9+, DragonFly BSD,
and FreeBSD 12+ (1.15.1).

Inappropriate use of this option may have its security
implications.

so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]
this parameter (1.1.11) configures the “TCP keepalive” behavior
for the listening socket.
If this parameter is omitted then the operating system’s settings will be
in effect for the socket.
If it is set to the value “on”, the
SO_KEEPALIVE option is turned on for the socket.
If it is set to the value “off”, the
SO_KEEPALIVE option is turned off for the socket.
Some operating systems support setting of TCP keepalive parameters on
a per-socket basis using the TCP_KEEPIDLE,
TCP_KEEPINTVL, and TCP_KEEPCNT socket options.
On such systems (currently, Linux 2.4+, NetBSD 5+, and
FreeBSD 9.0-STABLE), they can be configured
using the keepidle, keepintvl, and
keepcnt parameters.
One or two parameters may be omitted, in which case the system default setting
for the corresponding socket option will be in effect.
For example,

so_keepalive=30m::10

will set the idle timeout (TCP_KEEPIDLE) to 30 minutes,
leave the probe interval (TCP_KEEPINTVL) at its system default,
and set the probes count (TCP_KEEPCNT) to 10 probes.

Example:

listen 127.0.0.1 default_server accept_filter=dataready backlog=1024;
Syntax: location [
= |
~ |
~* |
^~
] uri { ... }

location @name { ... }
Default:

Context: server, location

Sets configuration depending on a request URI.

The matching is performed against a normalized URI,
after decoding the text encoded in the “%XX” form,
resolving references to relative path components “.
and “..”, and possible
compression of two or more
adjacent slashes into a single slash.

A location can either be defined by a prefix string, or by a regular expression.
Regular expressions are specified with the preceding
~*” modifier (for case-insensitive matching), or the
~” modifier (for case-sensitive matching).
To find location matching a given request, nginx first checks
locations defined using the prefix strings (prefix locations).
Among them, the location with the longest matching
prefix is selected and remembered.
Then regular expressions are checked, in the order of their appearance
in the configuration file.
The search of regular expressions terminates on the first match,
and the corresponding configuration is used.
If no match with a regular expression is found then the
configuration of the prefix location remembered earlier is used.

location blocks can be nested, with some exceptions
mentioned below.

For case-insensitive operating systems such as macOS and Cygwin,
matching with prefix strings ignores a case (0.7.7).
However, comparison is limited to one-byte locales.

Regular expressions can contain captures (0.7.40) that can later
be used in other directives.

If the longest matching prefix location has the “^~” modifier
then regular expressions are not checked.

Also, using the “=” modifier it is possible to define
an exact match of URI and location.
If an exact match is found, the search terminates.
For example, if a “/” request happens frequently,
defining “location = /” will speed up the processing
of these requests, as search terminates right after the first
comparison.
Such a location cannot obviously contain nested locations.

In versions from 0.7.1 to 0.8.41, if a request matched the prefix
location without the “=” and “^~
modifiers, the search also terminated and regular expressions were
not checked.

Let’s illustrate the above by an example:

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* .(gif|jpg|jpeg)$ {
    [ configuration E ]
}

The “/” request will match configuration A,
the “/index.html” request will match configuration B,
the “/documents/document.html” request will match
configuration C,
the “/images/1.gif” request will match configuration D, and
the “/documents/1.jpg” request will match configuration E.

The “@” prefix defines a named location.
Such a location is not used for a regular request processing, but instead
used for request redirection.
They cannot be nested, and cannot contain nested locations.

If a location is defined by a prefix string that ends with the slash character,
and requests are processed by one of
proxy_pass,
fastcgi_pass,
uwsgi_pass,
scgi_pass,
memcached_pass, or
grpc_pass,
then the special processing is performed.
In response to a request with URI equal to this string,
but without the trailing slash,
a permanent redirect with the code 301 will be returned to the requested URI
with the slash appended.
If this is not desired, an exact match of the URI and location could be
defined like this:

location /user/ {
    proxy_pass http://user.example.com;
}

location = /user {
    proxy_pass http://login.example.com;
}
Syntax: log_not_found on | off;
Default:
log_not_found on;
Context: http, server, location

Enables or disables logging of errors about not found files into
error_log.

Syntax: log_subrequest on | off;
Default:
log_subrequest off;
Context: http, server, location

Enables or disables logging of subrequests into
access_log.

Syntax: max_ranges number;
Default:

Context: http, server, location

This directive appeared in version 1.1.2.

Limits the maximum allowed number of ranges in byte-range requests.
Requests that exceed the limit are processed as if there were no
byte ranges specified.
By default, the number of ranges is not limited.
The zero value disables the byte-range support completely.

Syntax: merge_slashes on | off;
Default:
merge_slashes on;
Context: http, server

Enables or disables compression of two or more adjacent slashes
in a URI into a single slash.

Note that compression is essential for the correct matching of prefix string
and regular expression locations.
Without it, the “//scripts/one.php” request would not match

location /scripts/ {
    ...
}

and might be processed as a static file.
So it gets converted to “/scripts/one.php”.

Turning the compression off can become necessary if a URI
contains base64-encoded names, since base64 uses the “/
character internally.
However, for security considerations, it is better to avoid turning
the compression off.

If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.

Syntax: msie_padding on | off;
Default:
msie_padding on;
Context: http, server, location

Enables or disables adding comments to responses for MSIE clients with status
greater than 400 to increase the response size to 512 bytes.

Syntax: msie_refresh on | off;
Default:
msie_refresh off;
Context: http, server, location

Enables or disables issuing refreshes instead of redirects for MSIE clients.

Syntax: open_file_cache off;
open_file_cache
max=N
[inactive=time];
Default:
open_file_cache off;
Context: http, server, location

Configures a cache that can store:

  • open file descriptors, their sizes and modification times;
  • information on existence of directories;
  • file lookup errors, such as “file not found”, “no read permission”,
    and so on.

    Caching of errors should be enabled separately by the
    open_file_cache_errors
    directive.

The directive has the following parameters:

max
sets the maximum number of elements in the cache;
on cache overflow the least recently used (LRU) elements are removed;
inactive
defines a time after which an element is removed from the cache
if it has not been accessed during this time;
by default, it is 60 seconds;
off
disables the cache.

Example:

open_file_cache          max=1000 inactive=20s;
open_file_cache_valid    30s;
open_file_cache_min_uses 2;
open_file_cache_errors   on;
Syntax: open_file_cache_errors on | off;
Default:
open_file_cache_errors off;
Context: http, server, location

Enables or disables caching of file lookup errors by
open_file_cache.

Syntax: open_file_cache_min_uses number;
Default:
open_file_cache_min_uses 1;
Context: http, server, location

Sets the minimum number of file accesses during
the period configured by the inactive parameter
of the open_file_cache directive, required for a file
descriptor to remain open in the cache.

Syntax: open_file_cache_valid time;
Default:
open_file_cache_valid 60s;
Context: http, server, location

Sets a time after which
open_file_cache
elements should be validated.

Syntax: output_buffers number size;
Default:
output_buffers 2 32k;
Context: http, server, location

Sets the number and size of the
buffers used for reading a response from a disk.

Prior to version 1.9.5, the default value was 1 32k.

Syntax: port_in_redirect on | off;
Default:
port_in_redirect on;
Context: http, server, location

Enables or disables specifying the port in
absolute redirects issued by nginx.

The use of the primary server name in redirects is controlled by
the server_name_in_redirect directive.

Syntax: postpone_output size;
Default:
postpone_output 1460;
Context: http, server, location

If possible, the transmission of client data will be postponed until
nginx has at least size bytes of data to send.
The zero value disables postponing data transmission.

Syntax: read_ahead size;
Default:
read_ahead 0;
Context: http, server, location

Sets the amount of pre-reading for the kernel when working with file.

On Linux, the
posix_fadvise(0, 0, 0, POSIX_FADV_SEQUENTIAL)
system call is used, and so the size parameter is ignored.

On FreeBSD, the
fcntl(O_READAHEAD,
size)
system call, supported since FreeBSD 9.0-CURRENT, is used.
FreeBSD 7 has to be
patched.

Syntax: recursive_error_pages on | off;
Default:
recursive_error_pages off;
Context: http, server, location

Enables or disables doing several redirects using the
error_page
directive.
The number of such redirects is limited.

Syntax: request_pool_size size;
Default:
request_pool_size 4k;
Context: http, server

Allows accurate tuning of per-request memory allocations.
This directive has minimal impact on performance
and should not generally be used.

Syntax: reset_timedout_connection on | off;
Default:
reset_timedout_connection off;
Context: http, server, location

Enables or disables resetting timed out connections
and connections
closed
with the non-standard code 444 (1.15.2).
The reset is performed as follows.
Before closing a socket, the
SO_LINGER
option is set on it with a timeout value of 0.
When the socket is closed, TCP RST is sent to the client, and all memory
occupied by this socket is released.
This helps avoid keeping an already closed socket with filled buffers
in a FIN_WAIT1 state for a long time.

It should be noted that timed out keep-alive connections are
closed normally.

Syntax: resolver
address ...
[valid=time]
[ipv4=on|off]
[ipv6=on|off]
[status_zone=zone];
Default:

Context: http, server, location

Configures name servers used to resolve names of upstream servers
into addresses, for example:

resolver 127.0.0.1 [::1]:5353;

The address can be specified as a domain name or IP address,
with an optional port (1.3.1, 1.2.2).
If port is not specified, the port 53 is used.
Name servers are queried in a round-robin fashion.

Before version 1.1.7, only a single name server could be configured.
Specifying name servers using IPv6 addresses is supported
starting from versions 1.3.1 and 1.2.2.

By default, nginx will look up both IPv4 and IPv6 addresses while resolving.
If looking up of IPv4 or IPv6 addresses is not desired,
the ipv4=off (1.23.1) or
the ipv6=off parameter can be specified.

Resolving of names into IPv6 addresses is supported
starting from version 1.5.8.

By default, nginx caches answers using the TTL value of a response.
An optional valid parameter allows overriding it:

resolver 127.0.0.1 [::1]:5353 valid=30s;

Before version 1.1.9, tuning of caching time was not possible,
and nginx always cached answers for the duration of 5 minutes.

To prevent DNS spoofing, it is recommended
configuring DNS servers in a properly secured trusted local network.

The optional status_zone parameter (1.17.1)
enables
collection
of DNS server statistics of requests and responses
in the specified zone.
The parameter is available as part of our
commercial subscription.

Syntax: resolver_timeout time;
Default:
resolver_timeout 30s;
Context: http, server, location

Sets a timeout for name resolution, for example:

resolver_timeout 5s;
Syntax: root path;
Default:
root html;
Context: http, server, location, if in location

Sets the root directory for requests.
For example, with the following configuration

location /i/ {
    root /data/w3;
}

The /data/w3/i/top.gif file will be sent in response to
the “/i/top.gif” request.

The path value can contain variables,
except $document_root and $realpath_root.

A path to the file is constructed by merely adding a URI to the value
of the root directive.
If a URI has to be modified, the
alias directive should be used.

Syntax: satisfy all | any;
Default:
satisfy all;
Context: http, server, location

Allows access if all (all) or at least one
(any) of the
ngx_http_access_module,
ngx_http_auth_basic_module,
ngx_http_auth_request_module,
or
ngx_http_auth_jwt_module
modules allow access.

Example:

location / {
    satisfy any;

    allow 192.168.1.0/32;
    deny  all;

    auth_basic           "closed site";
    auth_basic_user_file conf/htpasswd;
}
Syntax: send_lowat size;
Default:
send_lowat 0;
Context: http, server, location

If the directive is set to a non-zero value, nginx will try to minimize
the number of send operations on client sockets by using either
NOTE_LOWAT flag of the
kqueue method
or the SO_SNDLOWAT socket option.
In both cases the specified size is used.

This directive is ignored on Linux, Solaris, and Windows.

Syntax: send_timeout time;
Default:
send_timeout 60s;
Context: http, server, location

Sets a timeout for transmitting a response to the client.
The timeout is set only between two successive write operations,
not for the transmission of the whole response.
If the client does not receive anything within this time,
the connection is closed.

Syntax: sendfile on | off;
Default:
sendfile off;
Context: http, server, location, if in location

Enables or disables the use of
sendfile().

Starting from nginx 0.8.12 and FreeBSD 5.2.1,
aio can be used to pre-load data
for sendfile():

location /video/ {
    sendfile       on;
    tcp_nopush     on;
    aio            on;
}

In this configuration, sendfile() is called with
the SF_NODISKIO flag which causes it not to block on disk I/O,
but, instead, report back that the data are not in memory.
nginx then initiates an asynchronous data load by reading one byte.
On the first read, the FreeBSD kernel loads the first 128K bytes
of a file into memory, although next reads will only load data in 16K chunks.
This can be changed using the
read_ahead directive.

Before version 1.7.11, pre-loading could be enabled with
aio sendfile;.

Syntax: sendfile_max_chunk size;
Default:
sendfile_max_chunk 2m;
Context: http, server, location

Limits the amount of data that can be
transferred in a single sendfile() call.
Without the limit, one fast connection may seize the worker process entirely.

Prior to version 1.21.4, by default there was no limit.

Syntax: server { ... }
Default:

Context: http

Sets configuration for a virtual server.
There is no clear separation between IP-based (based on the IP address)
and name-based (based on the “Host” request header field)
virtual servers.
Instead, the listen directives describe all
addresses and ports that should accept connections for the server, and the
server_name directive lists all server names.
Example configurations are provided in the
“How nginx processes a request” document.

Syntax: server_name name ...;
Default:
server_name "";
Context: server

Sets names of a virtual server, for example:

server {
    server_name example.com www.example.com;
}

The first name becomes the primary server name.

Server names can include an asterisk (“*”)
replacing the first or last part of a name:

server {
    server_name example.com *.example.com www.example.*;
}

Such names are called wildcard names.

The first two of the names mentioned above can be combined in one:

server {
    server_name .example.com;
}

It is also possible to use regular expressions in server names,
preceding the name with a tilde (“~”):

server {
    server_name www.example.com ~^wwwd+.example.com$;
}

Regular expressions can contain captures (0.7.40) that can later
be used in other directives:

server {
    server_name ~^(www.)?(.+)$;

    location / {
        root /sites/$2;
    }
}

server {
    server_name _;

    location / {
        root /sites/default;
    }
}

Named captures in regular expressions create variables (0.8.25)
that can later be used in other directives:

server {
    server_name ~^(www.)?(?<domain>.+)$;

    location / {
        root /sites/$domain;
    }
}

server {
    server_name _;

    location / {
        root /sites/default;
    }
}

If the directive’s parameter is set to “$hostname” (0.9.4), the
machine’s hostname is inserted.

It is also possible to specify an empty server name (0.7.11):

server {
    server_name www.example.com "";
}

It allows this server to process requests without the “Host”
header field — instead of the default server — for the given address:port pair.
This is the default setting.

Before 0.8.48, the machine’s hostname was used by default.

During searching for a virtual server by name,
if the name matches more than one of the specified variants,
(e.g. both a wildcard name and regular expression match), the first matching
variant will be chosen, in the following order of priority:

  1. the exact name
  2. the longest wildcard name starting with an asterisk,
    e.g. “*.example.com
  3. the longest wildcard name ending with an asterisk,
    e.g. “mail.*
  4. the first matching regular expression
    (in order of appearance in the configuration file)

Detailed description of server names is provided in a separate
Server names document.

Syntax: server_name_in_redirect on | off;
Default:
server_name_in_redirect off;
Context: http, server, location

Enables or disables the use of the primary server name, specified by the
server_name directive,
in absolute redirects issued by nginx.
When the use of the primary server name is disabled, the name from the
“Host” request header field is used.
If this field is not present, the IP address of the server is used.

The use of a port in redirects is controlled by
the port_in_redirect directive.

Syntax: server_names_hash_bucket_size size;
Default:
server_names_hash_bucket_size 32|64|128;
Context: http

Sets the bucket size for the server names hash tables.
The default value depends on the size of the processor’s cache line.
The details of setting up hash tables are provided in a separate
document.

Syntax: server_names_hash_max_size size;
Default:
server_names_hash_max_size 512;
Context: http

Sets the maximum size of the server names hash tables.
The details of setting up hash tables are provided in a separate
document.

Syntax: server_tokens
on |
off |
build |
string;
Default:
server_tokens on;
Context: http, server, location

Enables or disables emitting nginx version on error pages and in the
“Server” response header field.

The build parameter (1.11.10) enables emitting
a build name
along with nginx version.

Additionally, as part of our
commercial subscription,
starting from version 1.9.13
the signature on error pages and
the “Server” response header field value
can be set explicitly using the string with variables.
An empty string disables the emission of the “Server” field.

Syntax: subrequest_output_buffer_size size;
Default:
subrequest_output_buffer_size 4k|8k;
Context: http, server, location

This directive appeared in version 1.13.10.

Sets the size of the buffer used for
storing the response body of a subrequest.
By default, the buffer size is equal to one memory page.
This is either 4K or 8K, depending on a platform.
It can be made smaller, however.

The directive is applicable only for subrequests
with response bodies saved into memory.
For example, such subrequests are created by
SSI.

Syntax: tcp_nodelay on | off;
Default:
tcp_nodelay on;
Context: http, server, location

Enables or disables the use of the TCP_NODELAY option.
The option is enabled when a connection is transitioned into the
keep-alive state.
Additionally, it is enabled on SSL connections,
for unbuffered proxying,
and for WebSocket proxying.

Syntax: tcp_nopush on | off;
Default:
tcp_nopush off;
Context: http, server, location

Enables or disables the use of
the TCP_NOPUSH socket option on FreeBSD
or the TCP_CORK socket option on Linux.
The options are enabled only when sendfile is used.
Enabling the option allows

  • sending the response header and the beginning of a file in one packet,
    on Linux and FreeBSD 4.*;
  • sending a file in full packets.
Syntax: try_files file ... uri;
try_files file ... =code;
Default:

Context: server, location

Checks the existence of files in the specified order and uses
the first found file for request processing; the processing
is performed in the current context.
The path to a file is constructed from the
file parameter
according to the
root and alias directives.
It is possible to check directory’s existence by specifying
a slash at the end of a name, e.g. “$uri/”.
If none of the files were found, an internal redirect to the
uri specified in the last parameter is made.
For example:

location /images/ {
    try_files $uri /images/default.gif;
}

location = /images/default.gif {
    expires 30s;
}

The last parameter can also point to a named location,
as shown in examples below.
Starting from version 0.7.51, the last parameter can also be a
code:

location / {
    try_files $uri $uri/index.html $uri.html =404;
}

Example in proxying Mongrel:

location / {
    try_files /system/maintenance.html
              $uri $uri/index.html $uri.html
              @mongrel;
}

location @mongrel {
    proxy_pass http://mongrel;
}

Example for Drupal/FastCGI:

location / {
    try_files $uri $uri/ @drupal;
}

location ~ .php$ {
    try_files $uri @drupal;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME     $fastcgi_script_name;
    fastcgi_param QUERY_STRING    $args;

    ... other fastcgi_param's
}

location @drupal {
    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to/index.php;
    fastcgi_param SCRIPT_NAME     /index.php;
    fastcgi_param QUERY_STRING    q=$uri&$args;

    ... other fastcgi_param's
}

In the following example,

location / {
    try_files $uri $uri/ @drupal;
}

the try_files directive is equivalent to

location / {
    error_page 404 = @drupal;
    log_not_found off;
}

And here,

location ~ .php$ {
    try_files $uri @drupal;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;

    ...
}

try_files checks the existence of the PHP file
before passing the request to the FastCGI server.

Example for WordPress and Joomla:

location / {
    try_files $uri $uri/ @wordpress;
}

location ~ .php$ {
    try_files $uri @wordpress;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    ... other fastcgi_param's
}

location @wordpress {
    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to/index.php;
    ... other fastcgi_param's
}
Syntax: types { ... }
Default:
types {
    text/html  html;
    image/gif  gif;
    image/jpeg jpg;
}
Context: http, server, location

Maps file name extensions to MIME types of responses.
Extensions are case-insensitive.
Several extensions can be mapped to one type, for example:

types {
    application/octet-stream bin exe dll;
    application/octet-stream deb;
    application/octet-stream dmg;
}

A sufficiently full mapping table is distributed with nginx in the
conf/mime.types file.

To make a particular location emit the
application/octet-stream
MIME type for all requests, the following configuration can be used:

location /download/ {
    types        { }
    default_type application/octet-stream;
}
Syntax: types_hash_bucket_size size;
Default:
types_hash_bucket_size 64;
Context: http, server, location

Sets the bucket size for the types hash tables.
The details of setting up hash tables are provided in a separate
document.

Prior to version 1.5.13,
the default value depended on the size of the processor’s cache line.

Syntax: types_hash_max_size size;
Default:
types_hash_max_size 1024;
Context: http, server, location

Sets the maximum size of the types hash tables.
The details of setting up hash tables are provided in a separate
document.

Syntax: underscores_in_headers on | off;
Default:
underscores_in_headers off;
Context: http, server

Enables or disables the use of underscores in client request header fields.
When the use of underscores is disabled, request header fields whose names
contain underscores are
marked as invalid and become subject to the
ignore_invalid_headers directive.

If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.

Syntax: variables_hash_bucket_size size;
Default:
variables_hash_bucket_size 64;
Context: http

Sets the bucket size for the variables hash table.
The details of setting up hash tables are provided in a separate
document.

Syntax: variables_hash_max_size size;
Default:
variables_hash_max_size 1024;
Context: http

Sets the maximum size of the variables hash table.
The details of setting up hash tables are provided in a separate
document.

Prior to version 1.5.13, the default value was 512.

Embedded Variables

The ngx_http_core_module module supports embedded variables
with names matching the Apache Server variables.
First of all, these are variables representing client request header
fields, such as $http_user_agent, $http_cookie,
and so on.
Also there are other variables:

$arg_name
argument name in the request line
$args
arguments in the request line
$binary_remote_addr
client address in a binary form, value’s length is always 4 bytes
for IPv4 addresses or 16 bytes for IPv6 addresses
$body_bytes_sent
number of bytes sent to a client, not counting the response header;
this variable is compatible with the “%B” parameter of the
mod_log_config
Apache module
$bytes_sent
number of bytes sent to a client (1.3.8, 1.2.5)
$connection
connection serial number (1.3.8, 1.2.5)
$connection_requests
current number of requests made through a connection (1.3.8, 1.2.5)
$connection_time
connection time in seconds with a milliseconds resolution (1.19.10)
$content_length
“Content-Length” request header field
$content_type
“Content-Type” request header field
$cookie_name
the name cookie
$document_root
root or alias directive’s value
for the current request
$document_uri
same as $uri
$host
in this order of precedence:
host name from the request line, or
host name from the “Host” request header field, or
the server name matching a request
$hostname
host name
$http_name
arbitrary request header field;
the last part of a variable name is the field name converted
to lower case with dashes replaced by underscores
$https
on
if connection operates in SSL mode,
or an empty string otherwise
$is_args
?” if a request line has arguments,
or an empty string otherwise
$limit_rate
setting this variable enables response rate limiting;
see limit_rate
$msec
current time in seconds with the milliseconds resolution (1.3.9, 1.2.6)
$nginx_version
nginx version
$pid
PID of the worker process
$pipe
p” if request was pipelined, “.
otherwise (1.3.12, 1.2.7)
$proxy_protocol_addr
client address from the PROXY protocol header (1.5.12)

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$proxy_protocol_port
client port from the PROXY protocol header (1.11.0)

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$proxy_protocol_server_addr
server address from the PROXY protocol header (1.17.6)

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$proxy_protocol_server_port
server port from the PROXY protocol header (1.17.6)

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$proxy_protocol_tlv_name
TLV from the PROXY Protocol header (1.23.2).
The name can be a TLV type name or its numeric value.
In the latter case, the value is hexadecimal
and should be prefixed with 0x:

$proxy_protocol_tlv_alpn
$proxy_protocol_tlv_0x01

SSL TLVs can also be accessed by TLV type name
or its numeric value,
both prefixed by ssl_:

$proxy_protocol_tlv_ssl_version
$proxy_protocol_tlv_ssl_0x21

The following TLV type names are supported:

  • alpn (0x01) —
    upper layer protocol used over the connection
  • authority (0x02) —
    host name value passed by the client
  • unique_id (0x05) —
    unique connection id
  • netns (0x30) —
    name of the namespace
  • ssl (0x20) —
    binary SSL TLV structure

The following SSL TLV type names are supported:

  • ssl_version (0x21) —
    SSL version used in client connection
  • ssl_cn (0x22) —
    SSL certificate Common Name
  • ssl_cipher (0x23) —
    name of the used cipher
  • ssl_sig_alg (0x24) —
    algorithm used to sign the certificate
  • ssl_key_alg (0x25) —
    public-key algorithm

Also, the following special SSL TLV type name is supported:

  • ssl_verify —
    client SSL certificate verification result,
    0 if the client presented a certificate
    and it was successfully verified,
    non-zero otherwise.

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$query_string
same as $args
$realpath_root
an absolute pathname corresponding to the
root or alias directive’s value
for the current request,
with all symbolic links resolved to real paths
$remote_addr
client address
$remote_port
client port
$remote_user
user name supplied with the Basic authentication
$request
full original request line
$request_body
request body

The variable’s value is made available in locations
processed by the
proxy_pass,
fastcgi_pass,
uwsgi_pass,
and
scgi_pass
directives when the request body was read to
a memory buffer.

$request_body_file
name of a temporary file with the request body

At the end of processing, the file needs to be removed.
To always write the request body to a file,
client_body_in_file_only needs to be enabled.
When the name of a temporary file is passed in a proxied request
or in a request to a FastCGI/uwsgi/SCGI server,
passing the request body should be disabled by the

proxy_pass_request_body off,

fastcgi_pass_request_body off,

uwsgi_pass_request_body off, or

scgi_pass_request_body off
directives, respectively.

$request_completion
OK” if a request has completed,
or an empty string otherwise
$request_filename
file path for the current request, based on the
root or alias
directives, and the request URI
$request_id
unique request identifier
generated from 16 random bytes, in hexadecimal (1.11.0)
$request_length
request length (including request line, header, and request body)
(1.3.12, 1.2.7)
$request_method
request method, usually
GET” or “POST
$request_time
request processing time in seconds with a milliseconds resolution
(1.3.9, 1.2.6);
time elapsed since the first bytes were read from the client
$request_uri
full original request URI (with arguments)
$scheme
request scheme, “http” or “https
$sent_http_name
arbitrary response header field;
the last part of a variable name is the field name converted
to lower case with dashes replaced by underscores
$sent_trailer_name
arbitrary field sent at the end of the response (1.13.2);
the last part of a variable name is the field name converted
to lower case with dashes replaced by underscores
$server_addr
an address of the server which accepted a request

Computing a value of this variable usually requires one system call.
To avoid a system call, the listen directives
must specify addresses and use the bind parameter.

$server_name
name of the server which accepted a request
$server_port
port of the server which accepted a request
$server_protocol
request protocol, usually
HTTP/1.0”,
HTTP/1.1”,
or
“HTTP/2.0”
$status
response status (1.3.2, 1.2.2)
$tcpinfo_rtt,
$tcpinfo_rttvar,
$tcpinfo_snd_cwnd,
$tcpinfo_rcv_space
information about the client TCP connection; available on systems
that support the TCP_INFO socket option
$time_iso8601
local time in the ISO 8601 standard format (1.3.12, 1.2.7)
$time_local
local time in the Common Log Format (1.3.12, 1.2.7)
$uri
current URI in request, normalized

The value of $uri may change during request processing,
e.g. when doing internal redirects, or when using index files.

В этом руководстве мы расскажем о различных способах того, как в PHP включить вывод ошибок. Мы также обсудим, как записывать ошибки в журнал (лог).

Как быстро показать все ошибки PHP

Самый быстрый способ отобразить все ошибки и предупреждения php — добавить эти строки в файл PHP:

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

Что именно делают эти строки?

Функция ini_set попытается переопределить конфигурацию, найденную в вашем ini-файле PHP.

Display_errors и display_startup_errors — это только две из доступных директив. Директива display_errors определяет, будут ли ошибки отображаться для пользователя. Обычно директива dispay_errors не должна использоваться для “боевого” режима работы сайта, а должна использоваться только для разработки.

display_startup_errors — это отдельная директива, потому что display_errors не обрабатывает ошибки, которые будут встречаться во время запуска PHP. Список директив, которые могут быть переопределены функцией ini_set, находится в официальной документации .

К сожалению, эти две директивы не смогут отображать синтаксические ошибки, такие как пропущенные точки с запятой или отсутствующие фигурные скобки.

Отображение ошибок PHP через настройки в php.ini

Если ошибки в браузере по-прежнему не отображаются, то добавьте директиву:

display_errors = on

Директиву display_errors следует добавить в ini-файл PHP. Она отобразит все ошибки, включая синтаксические ошибки, которые невозможно отобразить, просто вызвав функцию ini_set в коде PHP.

Актуальный INI-файл можно найти в выводе функции phpinfo (). Он помечен как “загруженный файл конфигурации” (“loaded configuration file”).

Отображать ошибки PHP через настройки в .htaccess

Включить или выключить отображение ошибок можно и с помощью файла .htaccess, расположенного в каталоге сайта.

php_flag display_startup_errors on
php_flag display_errors on

.htaccess также имеет директивы для display_startup_errors и display_errors.

Вы можете настроить display_errors в .htaccess или в вашем файле PHP.ini. Однако многие хостинг-провайдеры не разрешают вам изменять ваш файл PHP.ini для включения display_errors.

В файле .htaccess также можно включить настраиваемый журнал ошибок, если папка журнала или файл журнала доступны для записи. Файл журнала может быть относительным путем к месту расположения .htaccess или абсолютным путем, например /var/www/html/website/public/logs.

php_value error_log logs/all_errors.log

Включить подробные предупреждения и уведомления

Иногда предупреждения приводят к некоторым фатальным ошибкам в определенных условиях. Скрыть ошибки, но отображать только предупреждающие (warning) сообщения можно вот так:

error_reporting(E_WARNING);

Для отображения предупреждений и уведомлений укажите «E_WARNING | E_NOTICE».

Также можно указать E_ERROR, E_WARNING, E_PARSE и E_NOTICE в качестве аргументов. Чтобы сообщить обо всех ошибках, кроме уведомлений, укажите «E_ALL & ~ E_NOTICE», где E_ALL обозначает все возможные параметры функции error_reporting.

Более подробно о функции error_reporting ()

Функция сообщения об ошибках — это встроенная функция PHP, которая позволяет разработчикам контролировать, какие ошибки будут отображаться. Помните, что в PHP ini есть директива error_reporting, которая будет задана ​​этой функцией во время выполнения.

error_reporting(0);

Для удаления всех ошибок, предупреждений, сообщений и уведомлений передайте в функцию error_reporting ноль. Можно сразу отключить сообщения отчетов в ini-файле PHP или в .htaccess:

error_reporting(E_NOTICE);

PHP позволяет использовать переменные, даже если они не объявлены. Это не стандартная практика, поскольку необъявленные переменные будут вызывать проблемы для приложения, если они используются в циклах и условиях.

Иногда это также происходит потому, что объявленная переменная имеет другое написание, чем переменная, используемая для условий или циклов. Когда E_NOTICE передается в функцию error_reporting, эти необъявленные переменные будут отображаться.

error_reporting(E_ALL & ~E_NOTICE);

Функция сообщения об ошибках позволяет вам фильтровать, какие ошибки могут отображаться. Символ «~» означает «нет», поэтому параметр ~ E_NOTICE означает не показывать уведомления. Обратите внимание на символы «&» и «|» между возможными параметрами. Символ «&» означает «верно для всех», в то время как символ «|» представляет любой из них, если он истинен. Эти два символа имеют одинаковое значение в условиях PHP OR и AND.

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

Эти три строки кода делают одно и то же, они будут отображать все ошибки PHP. Error_reporting(E_ALL) наиболее широко используется разработчиками для отображения ошибок, потому что он более читабелен и понятен.

Включить ошибки php в файл с помощью функции error_log ()

У сайта на хостинге сообщения об ошибках не должны показываться конечным пользователям, но эта информация все равно должна быть записана в журнал (лог).

Простой способ использовать файлы журналов — использовать функцию error_log, которая принимает четыре параметра. Единственный обязательный параметр — это первый параметр, который содержит подробную информацию об ошибке или о том, что нужно регистрировать. Тип, назначение и заголовок являются необязательными параметрами.

error_log("There is something wrong!", 0);

Параметр type, если он не определен, будет по умолчанию равен 0, что означает, что эта информация журнала будет добавлена ​​к любому файлу журнала, определенному на веб-сервере.

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

Параметр 1 отправит журнал ошибок на почтовый ящик, указанный в третьем параметре. Чтобы эта функция работала, PHP ini должен иметь правильную конфигурацию SMTP, чтобы иметь возможность отправлять электронные письма. Эти SMTP-директивы ini включают хост, тип шифрования, имя пользователя, пароль и порт. Этот вид отчетов рекомендуется использовать для самых критичных ошибок.

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

Для записи сообщений в отдельный файл необходимо использовать тип 3. Третий параметр будет служить местоположением файла журнала и должен быть доступен для записи веб-сервером. Расположение файла журнала может быть относительным путем к тому, где этот код вызывается, или абсолютным путем.

Журнал ошибок PHP через конфигурацию веб-сервера

Лучший способ регистрировать ошибки — это определить их в файле конфигурации веб-сервера.

Однако в этом случае вам нужно попросить администратора сервера добавить следующие строки в конфигурацию.

Пример для Apache:

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

В nginx директива называется error_log.

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

Теперь вы знаете, как в PHP включить отображение ошибок. Надеемся, что эта информация была вам полезна.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ngentask exe ошибка приложения 0xe0434352
  • Nfsc exe системная ошибка