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.

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,7582 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

1931 silver badge7 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

5992 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

Daniel's user avatar

DanielDaniel

1111 silver badge3 bronze badges

4

Блог / Программирование / Настроить Nginx для вывода php ошибок в браузер (а не только в log)

Это не является настройкой nginx, а управляется из конфигурации php-fpm.

Настройте в файле php-fpm.conf (к примеру для 7.4 это /etc/php/7.4/fpm/php-fpm.conf):

php_flag[display_errors] = on

php_flag[display_startup_errors] = on

Написать комментарий


Данная запись опубликована в 07.04.2022 15:30 и размещена в Программирование.
Вы можете перейти в конец страницы и оставить ваш комментарий.

Мало букафф? Читайте есчо !

Crop модуль для картинок Drupal

Декабрь 2, 2017 г.

Искал по работе crop модуль, который позволит редактору сайта выполнять обрезку картинки в админке при загрузке изображения в форму публикации.

На Drupal.org …

Читать

В этом руководстве мы расскажем о различных способах того, как в 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 включить отображение ошибок. Надеемся, что эта информация была вам полезна.

I am using php-fpm 5.5.9 along with nginx 1.4.6 on my Ubuntu 14.04 machine. I have installed them using apt-get package manager. I am unable to get a stack trace of the error that my index.php script encounters in error log as well as on the browser. I searched and implemented a couple of solutions from stackoverflow and other articles but none of them worked for me. Here is my nginx conf along with my php-fpm conf file. Please help me out if I am doing any silly mistake.

Nginx Configuration:

location ~ .php$ {
        # With php5-fpm:
                #try_files $uri =404;
        include fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors on;
        fastcgi_read_timeout 600;
        fastcgi_send_timeout 600;
        proxy_connect_timeout  600;
        proxy_send_timeout  600s;
        proxy_read_timeout  600s;
        fastcgi_pass 127.0.0.1:7777;
        fastcgi_index index.php;
    }

PHP-FPM Configuration:

error_log = /tmp/php5-fpm.log

PHP-FPM pool Configuration:

catch_workers_output = yes 
slowlog = /var/log/php-fpm/$pool.log.slow
listen = 127.0.0.1:7777

php_flag[display_errors] = On 
php_admin_value[error_log] = /tmp/fpm-php.www.log 
php_admin_flag[log_errors] = On

Thanks in advance.

asked Jul 8, 2014 at 15:40

Tojo Chacko's user avatar

Try to put in your site’s configuration inside the server directive the following:

access_log  /var/log/nginx/your_site.log;

error_log   /var/log/nginx/your_site.log;

replace the your_site.log with the name of your virtualhost — domain name.

Full example:

php-fpm

/etc/php5/fpm/php-fpm.conf

[global]
pid = /var/run/php5-fpm.pid
error_log = /var/log/php5-fpm.log
include=/etc/php5/fpm/pool.d/*.conf

/etc/php5/fpm/pool.d

[www]
user = www-data
group = www-data
pm = dynamic
pm.max_children = 10
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 6

Virtual host

upstream php {
        server unix:/tmp/php-cgi.socket;
        server 127.0.0.1:9000;
}

server {
    listen   80; ## listen for ipv4; this line is default and implied

    root /srv/www/mysite;
    index index.php;

    server_name mysite.com www.mysite.com;

    access_log  /var/log/nginx/mysite_access.log;
    error_log   /var/log/nginx/mysite_error.log;

    location / {
         try_files $uri $uri/ /index.php?$args; 
    }

    error_page 404 /404.html;

    error_page 500 502 503 504 /50x.html;

    location = /50x.html {
              root /usr/share/nginx/www;
        }



        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9$
        location ~ .php$ {
                #fastcgi_pass 127.0.0.1:9000;
                # With php5-fpm:
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
                 }
        location ~* .(js|css|png|jpg|jpeg|gif|ico)$ {
                expires max;
        access_log off;
                log_not_found off;
        }
}

answered Jul 8, 2014 at 16:05

Stef K's user avatar

Stef KStef K

4,7762 gold badges25 silver badges36 bronze badges

5

If you want the execution errors of a script, that’s configured on /etc/php5/fpm/php.ini.

If you want errors on a log file, edit php.ini :

display_errors  = off 
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
error_log = /path/to/some/file.log

If you want them on the browser, edit php.ini :

display_errors  = on
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

or, adding it on top of the script :

ini_set('display_errors',1);
error_reporting( E_ALL & ~E_DEPRECATED & ~E_STRICT );

I don’t know a way to log the stack trace directly on the logfile , but here there’s a way that you can implement defining your own error handler.

Community's user avatar

answered Aug 4, 2015 at 9:00

bistoco's user avatar

bistocobistoco

1,51115 silver badges21 bronze badges

Понравилась статья? Поделить с друзьями:
  • Nfsc exe ошибка при запуске приложения 0xc000007b
  • Nfs14 exe ошибка при запуске приложения 0xc000007b
  • Nfs windows ошибка сети 53
  • Nfs underground ошибка speed exe
  • Nfs underground 2 ошибка установки win 10