Php load ini files

How do I include a php.ini file in another php.ini file?

I’m interested how RHEL/Fedora accomplishes the /etc/php.d/* include. Did they patch PHP to make this possible?

@gahooa that’s the question that I had leading me here. Did you ever learn how they accomplish the /etc/php.d/* include?

see the accepted answer below, this answers your question too. U can also do php -i (phpinfo() ) and see how the php was built

6 Answers 6

I don’t think you can «include» .ini files from the main php.ini file.

One possible solution, though, might be to use this option on the configure line, when compiling PHP:

--with-config-file-scan-dir=PATH Set the path where to scan for configuration files 

If this option is used at compile-time, PHP will look for every .ini file in this directory, in addition to the «normal» php.ini file.

I suppose this is what is used by Ubuntu, for instance, which uses a different .ini file for each downloaded extension, instead of modifying php.ini.

The path to the php.ini file is being defined with this option, on the configure line:

--with-config-file-path=PATH Set the path in which to look for php.ini [PREFIX/lib] 

Still, it probably means you’ll have to re-compile PHP — which is not that hard, btw — the hardest part being to get the dependencies you need.

And, here is a post on the internals@ mailling-list that says the same thing as I do: config files and PHP_CONFIG_FILE_SCAN_DIR

Источник

Php load ini files

Файл конфигурации ( php.ini ) считывается при запуске PHP. Для версий серверных модулей PHP это происходит только один раз при запуске веб-сервера. Для CGI и CLI версий это происходит при каждом вызове.

  • По месту расположения модуля SAPI ( PHPIniDir директива Apache 2, -c параметр командной строки CGI и CLI)
  • Переменная среды PHPRC .
  • Местоположение файла php.ini может быть указано для различных версий PHP. Корневой ключ реестра зависит от разрядности операционной системы и установки PHP. Для 32-разрядного PHP на 32-разрядной Windows или 64-разрядного PHP и 64-разрядной Windows используйте [(HKEY_LOCAL_MACHINE\SOFTWARE\PHP] . Для 32-разрядного PHP на 64-разрядной Windows [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\PHP] . Следующие ключи реестра исследуются при поиске для установок с совпадающей разрядностью: [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z] , [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y] и [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x] , где x, y и z подразумевают major, minor и release версии PHP. Для 32-разрядного PHP на 64-разрядной Windows ключи реестра будут другими: [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6421Node\PHP\x.y.z] , [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6421Node\PHP\x.y] и [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6421Node\PHP\x] . Если также имеется значение IniFilePath в любом из этих ключей, то местонахождение php.ini будет определено первым ключом по порядку (только для Windows).
  • [HKEY_LOCAL_MACHINE\SOFTWARE\PHP] или [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\PHP] , значение IniFilePath (только для Windows).
  • Текущая директория (исключая CLI).
  • Директория веб-сервера (для модулей SAPI) или директория PHP (иначе в Windows).
  • В директории Windows ( C:\windows или C:\winnt ) (для Windows) или —with-config-file-path с выбором при компиляции.
Читайте также:  Linux проверить версию python

Если файл php-SAPI.ini существует (где SAPI — это тип интерфейса, который используется, например, php-cli.ini или php-apache.ini ), то он используется вместо php.ini . Тип интерфейса между веб-сервером и PHP может быть определён с помощью функции php_sapi_name() .

Замечание:

Веб-сервер Apache изменяет текущую директорию на корневую при запуске, в результате чего PHP считывает php.ini из корневой файловой системы, если файл существует.

В php.ini можно использовать переменные окружения, как показано ниже.

Пример #1 Переменные окружения php.ini

; PHP_MEMORY_LIMIT взята из переменных окружения memory_limit = $

Директивы php.ini , обрабатываемые модулями, описаны на соответствующих страницах модулей. Список директив ядра имеется в приложении. Не все директивы PHP документированы в этом руководстве: для ознакомления с полным списком директив доступных в вашей версии PHP, прочитайте комментарии вашего php.ini . Кроме того, вы можете найти полезной » последнюю версию php.ini из Git.

Пример #2 Пример php.ini

; любой текст в строке после точки с запятой (;) без кавычек игнорируется [php] ; маркеры разделов (текст в квадратных скобках) также игнорируется ; Могут быть установлены следующие логические значения: ; true, on, yes ; или false, off, no, none register_globals = off track_errors = yes ; вы можете заключать строки в двойные кавычки include_path = ".:/usr/local/lib/php" ; обратный слеш обрабатывается так же, как любые другие символы include_path = ".;c:\php\lib"

Возможно обращаться к существующим ini-переменным из ini-файлов. Пример: open_basedir = $ «:/new/dir» .

Сканирование директорий

Существует возможность сконфигурировать PHP для сканирования директорий в поисках .ini-файлов после считывания php.ini . Это можно сделать на моменте компиляции, указав опцию —with-config-file-scan-dir. Сканирование директорий может быть переопределено во время исполнения установкой переменной среды PHP_INI_SCAN_DIR .

Можно сканировать несколько директорий, разделяя их разделителем, используемом в вашей операционной системе ( ; в Windows, NetWare и RISC OS; : на всех остальных платформах; в PHP есть константа PATH_SEPARATOR , которую можно использовать) Если PHP_INI_SCAN_DIR пуста, то PHP также будет сканировать директорию, заданную на этапе компиляции с помощью —with-config-file-scan-dir.

В каждой директории PHP сканирует все файлы заканчивающиеся на .ini в алфавитном порядке. Список всех загруженных файлов в том порядке, в котором они были загружены, доступен с помощью функции php_ini_scanned_files() , либо при запуске PHP с опцией —ini.

Допустим, что PHP сконфигурирован с --with-config-file-scan-dir=/etc/php.d, и разделитель путей . $ php PHP загрузит все файлы /etc/php.d/*.ini как конфигурационные. $ PHP_INI_SCAN_DIR=/usr/local/etc/php.d php PHP загрузит все файлы /usr/local/etc/php.d/*.ini как конфигурационные. $ PHP_INI_SCAN_DIR=:/usr/local/etc/php.d php PHP загрузит все файлы /etc/php.d/*.ini, а потом /usr/local/etc/php.d/*.ini как конфигурационные. $ PHP_INI_SCAN_DIR=/usr/local/etc/php.d: php PHP загрузит все файлы /usr/local/etc/php.d/*.ini, а потом /etc/php.d/*.ini как конфигурационные.

Источник

How to read and write to an ini file with PHP

I’ve been looking around the official php documentation but I’m unable to find what I’m looking for. http://php.net/manual/en/function.parse-ini-file.php I just want a function to edit and read the value from the php ini file, for instance,

[default_colors] sitebg = #F8F8F8 footerbg = #F8F8F8 link = #F8F8F8 url = #F8F8F8 bg = #F8F8F8 text = #F8F8F8 border = #F8F8F8 lu_link = #F8F8F8 lu_url = #F8F8F8 lu_bg = #F8F8F8 lu_text = #f505f5 lu_border = #F8F8F8 
  1. How do I read the value belonging to «lu_link» or «footerbg»?
  2. How to I write a new value for these places?
Читайте также:  Как умножить строки в java

6 Answers 6

You can simply use parse_ini_file with PHP4/5.

$ini_array = parse_ini_file("sample.ini"); print_r($ini_array); 

To write back an array of objects back to the ini file, use below as a very fast & easy solution:

function write_php_ini($array, $file) < $res = array(); foreach($array as $key =>$val) < if(is_array($val)) < $res[] = "[$key]"; foreach($val as $skey =>$sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"'); > else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"'); > safefilerewrite($file, implode("\r\n", $res)); > function safefilerewrite($fileName, $dataToSave) < if ($fp = fopen($fileName, 'w')) < $startTime = microtime(TRUE); do < $canWrite = flock($fp, LOCK_EX); // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load if(!$canWrite) usleep(round(rand(0, 100)*1000)); >while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5)); //file was locked so now we can store information if ($canWrite) < fwrite($fp, $dataToSave); flock($fp, LOCK_UN); >fclose($fp); > > 

thanks but I had already searched this and since I’m very new to php it is very confusign at a glance

safefilerewrite is a user made function. If you go to the php doc listed in the answer and search the comments for safefilerewrite you will see one possible example.

The PEAR Config_Lite package can do almost all the work (both reading and writing) for you super-easily. Check it out here: http://pear.php.net/package/Config_Lite

OMG this looks GREAT! but I’m very new to php and programming in general, what is PEAR? Whats is a framework? Will this work in my hosted site?

ok I’ve got it instaled and downloaded the module and got it reading a ini file already 😛 Thanks. But can you teach me more about what is a framework and why did I had to install pear? Why is config_lite called a «module» ? I would really like to learn this the proper way please.

Sure, no problem. Simply put, PEAR is a collection of «modules» — generalized, but purpose-built PHP code that’s already been written for you, to automate and simplify numerous tasks. You had to install it separately because it’s written and maintained by enthusiasts, and because the solutions it provides are too large and too specific to really make sense as part of the core PHP language. Config_lite is only one out of many, many modules; among them is the full Config module, which is like config_lite but with more features.

I have a big problem with saving the ini file, and I’ve tried this outised pear, it adds «» around keyvalues for keyvalues that where not wrapped around «».

 $key='option'; $val='1.2.3.4.5'; system("sed -ie 's/\(=\)\(.*\)/\1/' file.in"); 

Below is an implementation of write_ini_file() which PHP is currently lacking, it will create an almost identical (except comments) of the input:

  • Supports cross platform ( PHP_EOL ) new lines added between sections.
  • Handles both index and key value arrays.
  • Handles CONSTANT style values.
  • And file locking to stay consistent.
 // check second argument is array if (!is_array($array)) < throw new \InvalidArgumentException('Function argument 2 must be an array.'); >// process array $data = array(); foreach ($array as $key => $val) < if (is_array($val)) < $data[] = "[$key]"; foreach ($val as $skey =>$sval) < if (is_array($sval)) < foreach ($sval as $_skey =>$_sval) < if (is_numeric($_skey)) < $data[] = $skey.'[] = '.(is_numeric($_sval) ? $_sval : (ctype_upper($_sval) ? $_sval : '"'.$_sval.'"')); >else < $data[] = $skey.'['.$_skey.'] = '.(is_numeric($_sval) ? $_sval : (ctype_upper($_sval) ? $_sval : '"'.$_sval.'"')); >> > else < $data[] = $skey.' = '.(is_numeric($sval) ? $sval : (ctype_upper($sval) ? $sval : '"'.$sval.'"')); >> > else < $data[] = $key.' = '.(is_numeric($val) ? $val : (ctype_upper($val) ? $val : '"'.$val.'"')); >// empty line $data[] = null; > // open file pointer, init flock options $fp = fopen($file, 'w'); $retries = 0; $max_retries = 100; if (!$fp) < return false; >// loop until get lock, or reach max retries do < if ($retries >0) < usleep(rand(1, 5000)); >$retries += 1; > while (!flock($fp, LOCK_EX) && $retries // got lock, write data fwrite($fp, implode(PHP_EOL, $data).PHP_EOL); // release lock flock($fp, LOCK_UN); fclose($fp); return true; > > 
; This is a sample configuration file ; Comments start with ';', as in php.ini [first_section] one = 1 five = 5 animal = BIRD [second_section] path = "/usr/local/bin" URL = "http://www.example.com/~username" [third_section] phpversion[] = "5.0" phpversion[] = "5.1" phpversion[] = "5.2" phpversion[] = "5.3" urls[svn] = "http://svn.php.net" urls[git] = "http://git.php.net" 

Example usage:

// load ini file values into array $config = parse_ini_file('config.ini', true); // add some additional values $config['main']['foobar'] = 'baz'; $config['main']['const']['a'] = 'UPPERCASE'; $config['main']['const']['b'] = 'UPPER_CASE WITH SPACE'; $config['main']['array'][] = 'Some Value'; $config['main']['array'][] = 'ADD'; $config['third_section']['urls']['docs'] = 'http://php.net'; // write ini file write_ini_file('config.ini', $config); 

Resulting .ini file:

[first_section] one = 1 five = 5 animal = BIRD [second_section] path = "/usr/local/bin" URL = "http://www.example.com/~username" [third_section] phpversion[] = 5.0 phpversion[] = 5.1 phpversion[] = 5.2 phpversion[] = 5.3 urls[svn] = "http://svn.php.net" urls[git] = "http://git.php.net" urls[docs] = "http://php.net" [main] foobar = "baz" const[a] = UPPERCASE const[b] = "UPPER_CASE WITH SPACE" array[] = "Some Value" array[] = ADD 

Источник

Читайте также:  Np eye python numpy

How can I know which ‘php.ini’ file is used?

I search the path where the php.ini file is located in our Linux Ubuntu server, and I found many php.ini files when executing the command find / -name php.ini . So how can I know exactly from a PHP script web page where the php.ini is located?

7 Answers 7

For the webserver-SAPIs use phpinfo()

bash-3.2# php --ini Configuration File (php.ini) Path: /usr/local/php5/lib Loaded Configuration File: /usr/local/php5/lib/php.ini Scan for additional .ini files in: /usr/local/php5/php.d Additional .ini files parsed: /usr/local/php5/php.d/10-extension_dir.ini, /usr/local/php5/php.d/20-extension-opcache.ini, /usr/local/php5/php.d/40-openssl.ini, /usr/local/php5/php.d/50-extension-apcu.ini, /usr/local/php5/php.d/50-extension-curl.ini, /usr/local/php5/php.d/50-extension-gmp.ini, /usr/local/php5/php.d/50-extension-imap.ini, /usr/local/php5/php.d/50-extension-intl.ini, /usr/local/php5/php.d/50-extension-mcrypt.ini, /usr/local/php5/php.d/50-extension-mssql.ini, /usr/local/php5/php.d/50-extension-pdo_pgsql.ini, /usr/local/php5/php.d/50-extension-pgsql.ini, /usr/local/php5/php.d/50-extension-propro.ini, /usr/local/php5/php.d/50-extension-raphf.ini, /usr/local/php5/php.d/50-extension-readline.ini, /usr/local/php5/php.d/50-extension-xdebug.ini, /usr/local/php5/php.d/50-extension-xsl.ini, /usr/local/php5/php.d/60-extension-pecl_http.ini, /usr/local/php5/php.d/99-liip-developer.ini 

Источник

Оцените статью