どのようにPHP変数をNGINXから取得しますか

Nginx で PHP の変数を取得するには、2 つの方法があります。

  1. fastcgi_param ディレクティブを含む ngx_http_fastcgi_module モジュールを使用します:
  2. Nginxの設定ファイルでfastcgi_paramディレクティブを使用して、PHPの変数をFastCGIプロセスに渡します。たとえば:location / {
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PHP_VAR $php_var;
    include fastcgi_params;
    }
  3. PHP スクリプトでは、変数の値を取得するために、$_SERVER[‘PHP_VAR’] が使用できます。
  4. ngx_http_rewrite_moduleモジュールのsetディレクティブを使用します:
  5. set ディレクティブを使用して、Nginx の設定ファイルで PHP の変数を Nginx の変数に設定します。たとえば、location / { set $php_var $arg_php_var; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PHP_VAR $php_var; include fastcgi_params; }
  6. PHPスクリプトでは$_SERVER[‘PHP_VAR’]を使用してその変数の値を取得することができます。

なお、上記方法はPHP変数をNginxの構成レベルで渡すものであって、PHPスクリプトから直接取得するものではありません。

bannerAds