A
A
AlexanderY2014-05-11 11:06:44
PHP
AlexanderY, 2014-05-11 11:06:44

Why does nginx throw an error FastCGI sent in stderr: "PHP message: PHP Notice: Undefined variable: object_id?

background
На одном сервере с типичной конфигурацией (Apache + php + mysql) живет некоторый проект, написанный довольно давно, не знаю кем. Апач потребляет довольно много RAM, поэтому было решено попробовать перенести проект на сервер с Nginx + php-fpm, чтобы не арендовать все более и более дорогой VPS со временем. Судя по качеству кода, писал сайт такой же непрофессиональный программист, как я — непрофессиональный админ. Но вариант "выкинуть все и переписать с нуля" не рассматривается.

In short, I smoked this article and decided why not spend Saturday setting up the server. In principle, the nginx and php-fpm web server itself was configured, test php scripts work "with a bang", all static is given normally.
I uploaded the site to a test subdomain and immediately a problem appeared : the page opens, I see the template, all styles and statics are loaded, but there is no content on the page that is stored in the database. I thought that there were some problems in connecting to mysql, but in the logs (/var/log/nginx/error.log
) I found only this:
Error text
2014/05/11 11:33:59 [error] 23791#0: *8 FastCGI sent in stderr: "PHP message: PHP Notice: Undefined variable: object_id in /var/www/example_ru/data/www/test.example.ru/shablon/web/conteyner/main.php on line 89" while reading response header from upstream, client: xx.xx.xx.xx, server: test.example.ru, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "test.example.ru"

The second problem is that apart from the main page nothing was opened, everywhere it returned a 404 error. I did not transfer the rewrite rules from htaccess and thought that at least I know where this problem is coming from. At the same time, I found out that the $object_id variable should be defined in index.php in a muddy construction consisting of ifs and issets. Therefore, I believe that the variable is not defined for the same reason that secondary pages are not opened.
htaccess code from old server
php_value register_globals Off
ErrorDocument 404 404.html
AddDefaultCharset utf-8
AddCharset utf-8 *
<IfModule mod_charset.c>
CharsetSourceEnc utf-8
CharsetDefault utf-8
</IfModule>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\.html$ index.php?cat_name=$1 [NC,L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?cat_name=$1 [NC,L,QSA]

New server nginx.conf code
user	www-data;

worker_processes  auto;
timer_resolution 100ms;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    server_tokens off;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    gzip  on;
    gzip_http_version 1.1;
    gzip_disable msie6;
    gzip_types text/plain application/xml application/x-javascript text/css;

   include /etc/nginx/conf.d/stub.conf;

  include /usr/local/ispmgr/etc/nginx.domain;
  client_max_body_size 16M;
  log_format isp '$bytes_sent $request_length';
  
  include common/upstream;
  
  include /etc/nginx/sites-enabled/*;
}

common/upstream code
upstream php-fpm
{
  #php5-fpm сервер
  server unix:/var/run/php5-fpm.sock;
}

Code /etc/nginx/sites-enabled/test.example.ru
server
{
  listen  80;
  server_name  www.test.example.ru;
  rewrite ^ http://test.example.ru$request_uri? permanent; #301 redirect
}

server
{
  # Порты
  listen	80;
  disable_symlinks if_not_owner from=$root_path;
  set $root_path /var/www/example_ru/data/www/test.example.ru;
  root	$root_path;
  index	index.php index.html index.htm;
  server_name	test.example.ru;

  client_max_body_size	30m; # максимальный объем файла для загрузки 30 mb
  
  location "/"
  {
    try_files	$uri $uri/	=404; # проверить есть ли файл из запроса на диске, иначе 404
  }
  
  include common/locations/deny;

  # Направление PHP-скрипта для обработки FastCGI или PHP-FPM серверу
  location ~ \.php$
  {
    # Решение проблемы с уязвимостью (см. http://forum.nginx.org/read.php?2,88845,page=3)
    # Не будет работать (ошибка 404) если файлы хранятся на другом сервере
    try_files	$uri $uri/ $uri/index.php?q=$uri&$args $uri/index.php	=404;
    
    include common/php-fpm;
  }
}

If you add the following code (by the way, it is not recommended to write this way , but this is just a demonstration so far) in "location /", then when you try to go to any page other than the main one, index.php (named XUDadWDM) is downloaded.
spoiler
if (!-e $request_filename){ 
      rewrite ^/(.*)\.html$ /index.php?cat_name=$1 break; 
    } 
    
    if (!-e $request_filename){ 
      rewrite ^(.*)$ /index.php?cat_name=$1 break; 
    }

Этот кусок я взял из winginx.com/ru/htaccess

If this code is not added, then only the main page opens, while others return a 404 error.
And finally, the common/php-fpm code
# Настройки порта или сокета PHP-FPM производятся в файле "/etc/php5/fpm/pool.d/www.conf"
fastcgi_pass	php-fpm;
# Порядок важен - строчка "include fastcgi_params" должна быть первой
include fastcgi_params;
fastcgi_split_path_info			^(.+?\.php)(/.*)?$;
fastcgi_param	SCRIPT_FILENAME		$document_root$fastcgi_script_name;
fastcgi_param	PATH_TRANSLATED		$document_root$fastcgi_script_name;
# См. http://trac.nginx.org/nginx/ticket/321
set		$path_info		$fastcgi_path_info;
fastcgi_param	PATH_INFO		$path_info;
# Указание дополнительных переменных окружения PHP
fastcgi_param	SERVER_ADMIN		xxx;
fastcgi_param	SERVER_SIGNATURE	nginx/$nginx_version;
fastcgi_index	index.php;

Actually, help to transfer Rewrite rules from Apache to Nginx, please. And if the error does not occur because of this, then because of what then?
PS I installed phpMyAdmin on another subdomain, everything worked right away without a single problem, so I almost rule out problems with working specifically with php or mysql.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Antony Ryabov, 2014-05-11
@tonymadbrain

www.winginx.com/en/htaccess

I
Igor, 2014-05-11
@merryjane

Try something like this:

server {
  listen 80;
  server_name test.example.ru;

  root /var/www/example_ru/data/www/test.example.ru;
  index index.php index.html index.htm;

  client_max_body_size	30m;

  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      	include fastcgi_params;
  fastcgi_read_timeout 60;
  fastcgi_send_timeout 60;

  location / {
    if (!-e $request_filename) {
      rewrite ^(.+)$ /index.php?cat_name=$1 last;
    }
    expires 72h;
  }

  location ~ \.php$ {
    if (!-e $request_filename) {
      rewrite ^(.+)$ /index.php?cat_name=$1 last;
    }
    fastcgi_pass unix:/var/run/php5-fpm.sock;
  }
}

And turn on logging to see which location the request falls into.

T
Toopie, 2018-01-20
@Toopie

PHP says that this variable has not been used anywhere before, that is, it has not been assigned a value anywhere before ($var = 'test';), you can turn off the warnings by inserting at the beginning of the code:
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question