PHP:可以在默认的 php.ini 文件中设置常量
我想要一个常量(一个字符串),它可用于服务器上的所有 PHP 脚本.
I want to have a constant (a string) that is available to all PHP-scripts on the server.
根据http://php.net/manual/en/function.parse-ini-file.php 如果你解析一个额外的 .ini 文件,这很容易,但是我不想解析一个额外的文件,我想在全局 php.ini 中设置我的常量无需解析脚本中的任何内容.(事实上,这就是重点,因为我需要常量来查找要包含/解析/等的内容:当我知道这个额外的 .ini 文件在哪里时,我就不再需要它了!)
According to http://php.net/manual/en/function.parse-ini-file.php this is quite easy if you parse an extra .ini file, however I don't want to parse an extra file, I want to set my constant in the global php.ini without having to parse anything in the scripts. (In fact that's the whole point because I need the constant to find the stuff to include/parse/etc: When I know where this extra .ini file would be, I don't need it anymore!)
只是在 php.ini 中创建一个新常量,然后尝试使用 ini_get() 访问它不起作用,还有其他方法吗?
Just inventing a new constant in php.ini and then trying to access it with ini_get() does not work, is there any other way?
我自己编译 Apache 和 PHP,因此我也可以在编译时设置常量和/或在必要时使用 Apache 常量.
I compile Apache and PHP myself, so I could also set the constant at compile-time and/or use Apache-constants if that is neccessary.
您可以使用 PHP auto_prepend_file
脚本在您的 PHP ini 中执行此操作,因为它将在您的任何用户级脚本之前运行:
You can use a PHP auto_prepend_file
script in your PHP ini to do this as it will be run before any of your user-land scripts:
指定在解析之前自动解析的文件名主文件.该文件被包含,就好像它是用 require 调用的一样函数,因此使用 include_path.
Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the require function, so include_path is used.
因此您可以添加如下 ini 行:
So you can add an ini line like:
auto_prepend_file="/home/user/script.php"
在/home/user/script.php:
The in /home/user/script.php:
define('CONSTANT_NAME', 'your nice value here');
现在在您的 PHP 脚本中,您可以从您喜欢的任何位置访问 CONSTANT_NAME
,因为它在所有 PHP 脚本中都可用.
Now in your PHP scripts you can access CONSTANT_NAME
from wherever you like as it is available in all PHP scripts.
我在使用基于 mod_rewrite 的大规模虚拟主机的临时服务器上使用此技术,因此我可以为我的 PHP 脚本提供准确的文档根目录.我之前在博文中讨论过这个问题.
I use this technique on my staging server that uses mod_rewrite based mass virtual hosting so I can give my PHP scripts an accurate document root. I have discussed this in a blog post before.