Linux как найти php ini

On the command line execute:

php --ini

You will get something like:

Configuration File (php.ini) Path: /etc/php5/cli
Loaded Configuration File:         /etc/php5/cli/php.ini
Scan for additional .ini files in: /etc/php5/cli/conf.d
Additional .ini files parsed:      /etc/php5/cli/conf.d/curl.ini,
/etc/php5/cli/conf.d/pdo.ini,
/etc/php5/cli/conf.d/pdo_sqlite.ini,
/etc/php5/cli/conf.d/sqlite.ini,
/etc/php5/cli/conf.d/sqlite3.ini,
/etc/php5/cli/conf.d/xdebug.ini,
/etc/php5/cli/conf.d/xsl.ini

That’s from my local dev-machine. However, the second line is the interesting one. If there is nothing mentioned, have a look at the first one. That is the path, where PHP looks for the php.ini file.

You can grep the same information using phpinfo() in a script and call it with a browser. It’s mentioned in the first block of the output. php -i does the same for the command line, but it’s quite uncomfortable.

PHP – это один из самых популярных языков программирования для создания сайтов и веб-приложений. На нем разработано множество готовых систем управления контентом для блогов, сайтов фирм или даже интернет-магазинов. Несмотря на то что у этого языка есть свои недостатки, он достаточно прост в освоении и поэтому очень часто используется для разработки новых сайтов.

Интерпретатор php может поставляться в виде модуля для Apache, выполнять скрипты из командной строки или в виде отдельного сервиса php-fpm. Эти сервисы отличаются своими возможностями, и предназначением, но для любого вида интерпретатора нужно задать базовые настройки, например, рабочая папка, включенные расширения, отображение ошибок и так далее. Все эти настройки задаются через файл php.ini. В этой инструкции мы рассмотрим как выполняется настройка файла php.ini в операционных системах Linux, хотя все информация подойдет и для Windows.

Если у вас еще не установлен интерпретатор языка программирования php, то вы можете ознакомиться со статьей установка lamp в Ubuntu 16.04.

Для каждой версии интерпретатора конфигурационный файл php.ini находится в отдельной папке. Но все конфигурационные файлы находятся в папке /etc/php, например, /etc/php5:

ls /etc/php5/

php

Папка conf.d содержит общие настройки для различных расширений и модулей, они не будут нас сейчас интересовать. Более интересны следующие три папки – apache, cli и fpm. В них содержатся конфигурационные файлы php.ini для каждого из этих интерпретаторов.

Если вы собираетесь использовать несколько из этих интерпретаторов, то вам придется указывать настройки для каждого из них отдельно. Вы можете убедиться, что в каждой из папок лежит файл php.ini.

Что касается синтаксиса файла, то он разделен на секции, сначала идет секция настройки php, которая разделена на подсекции в зависимости от типа настроек, дальше идут секции настройки разных модулей. Синтаксис самих настроек очень прост, он соответствует привычному синтаксису ini  файлов. Строка начинается с имени настройки, затем следует знак равно, а за ним значение:

имя_настройки=значение_параметра

Символами [] обозначается имя секции, например, [PHP], а символ ; означает комментарий, он и все символы после него не читаются интерпретатором. А теперь рассмотрим как выполняется настройка php.ini и переберем самые важные параметры.

Настройка файла php.ini

Для удобства ориентирования мы разобьем все параметры по категориях в зависимости от их назначения. Вам будет достаточно найти нужный параметр и изменить его значение. А теперь откройте файл настроек php, например, для модуля apache и перейдем к настройке. Чтобы избежать ошибок не добавляйте новые строки, а ищите уже существующие и изменяйте значения на нужные:

sudo gedit /etc/php5/apache/php.ini

php1

Сначала идет немного информации о самом файле в виде комментариев, затем интересующие нас настройки.

Вывод ошибок в php

Настройка php 7 обычно начинается с конфигурации вывода ошибок. Все настройки вывода ошибок находятся в разделе Error handling and logging. По умолчанию вывод ошибок на экран во время выполнения скрипта отключен. Это сделано для того, чтобы пользователи не смогли увидеть ничего лишнего. Вместо этого, все ошибки записываются в лог файл. Если вы используете php на домашнем компьютере, то такие меры не нужны и вы можете сразу выводить все на экран:

display_errors=off

php3

Замените off на on. В php используются различные типы ошибок, например, критические, предупреждения, ошибки синтаксиса, с помощью строки error_reporting вы можете включить вывод только определенных типов ошибок:

error_reporting = E_ALL  & ~E_DEPRECATED

Если нужно объединить несколько типов ошибок, то используйте символ &, а для отключения отображения поставьте перед типом знак ~. Приведенный выше пример отображает все ошибки (E_ALL), кроме сообщений об устаревших функциях (E_DEPRECATED). Вы можете отключить все типы использовав 0:

error_reporting = 0

Включите запись ошибок php в лог файл, если не выводите их на экран:

log_errors = On

Чтобы не засорять лог однотипными сообщениями можно игнорировать повторяющиеся ошибки в пределах одного исполнения:

ignore_repeated_errors = On

Ограничения ресурсов

php6

Если бы скрипты php никак не ограничивались в ресурсах, то они запросто могли бы перегрузить сервер и не дать ему нормально работать. Поэтому, по умолчанию php устанавливает жесткие ограничения, но, возможно, вам нужно будет их немного ослабить.

По умолчанию максимальное время выполнения скрипта – 30 секунд, сделаем минуту:

max_execution_time = 30

Если указать 0, то скрипт может выполняться бесконечно. Вы также можете ограничить время, на протяжении которого скрипт будет загружать данные, 60 секунд:

max_input_time=60

Максимальное количество переменных в GET и POST:

max_input_vars = 1000

Следующий параметр задает максимальное количество памяти, которую может использовать один скрипт во время своего выполнения, в мегабайтах:

memory_limit = 128M

Максимальный размер данных, передаваемых в POST запросе тоже ограничивается, размер по умолчанию – 8 Мегабайт:

post_max_size = 8M

Вы можете ограничить область действия php в системе с помощью опции openbase_dir, она указывает папку, выше которой скрипт не может получить доступ к файловой системе:

open_basedir = /var/www/

С помощью директив disable_functions и disable_classes вы можете отключить использование в скриптах определенных функций или классов, например, это может быть полезно для веб-хостингов. В этом примере мы отключаем использование функции ini_set, которая позволяет менять настройки php из скрипта:

disable_functions = ini_set

Директории по умолчанию

php4

Файл настройки php.ini позволяет указать пути в файловой системе по умолчанию для различных действий. Вы можете задать папки где система будет искать скрипты, если вы попытаетесь подключить их с помощью инструкции include:

include_path = ".:/usr/share/php5:/usr/share/php5/PEAR"

Папка с модулями php:

extension_dir="./"

Папка для записи временных файлов:

sys_temp_dir = "/tmp"

Загрузка файлов

php5

Для того чтобы пользователи могли загружать свои файлы на сервер, например, фото, нужно включить эту функцию в php:

file_uploads = On

Максимальный размер загружаемого файла:

upload_max_filesize = 2M

Максимальное количество файлов, которые может загрузить один скрипт:

max_file_uploads = 20

Настройка php.ini практически завершена, нам остались лишь расширения.

Настройка расширений

Расширения позволяют очень сильно увеличить функциональность php. Например, благодаря расширениям вы можете использовать в своих скриптах базы данных mysql, postgresql, mysqli, sqlite, графическую библиотеку gd и многое другое. Все это включается в этом разделе.

Для включения расширения достаточно убрать комментарий перед строкой с его командой, например:

extension=php_mysql.so
extension=php_mbstring.so
extension=php_pgsql.so

php2

Обратите внимание, что для windows расширение будет иметь формат dll, но для linux нужно использовать so. В следующих секциях идет настройка каждого из расширений, но мы их рассматривать не будем потому что они обычно не требуют настройки.

Выводы

В этой статье мы рассмотрели как выполняется настройка php на сервере или обычном компьютере для разработки веб-сайтов. Файл настроек php имеет довольно простую структуру и с ним довольно не сложно справиться. После завершения всех настроек и сохранения изменений не забудьте перезагрузить веб-сервер или сервис php-fpm.

Вообще говоря, php-fpm это отдельная тема, потому что там есть много дополнительных настроек, и, возможно, мы рассмотрим его в одной из следующих статей. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

I am currently trying to locate the correct php.ini file to edit it and restart apache so the changes will take place and I’m stumped.

I have found three different php.ini files (no idea why there are three)
this is how I found the files

$ sudo find / -name php.ini
/etc/php5/cli/php.ini
/etc/php5/apache2/php.ini
/etc/php5/cgi/php.ini

I also did….

$ sudo php -i | grep 'Configuration File'
Configuration File (php.ini) Path => /etc/php5/cli
Loaded Configuration File => /etc/php5/cli/php.ini

I changed all of them (just to be sure) to the settings I wanted.

I restarted apache using

sudo service apache2 restart

The results…

* Restarting web server apache2

I reloaded the page and it showed that the php.ini file was not updated.

I know this because I used

echo ini_get('post_max_size');

Which was supposed to be changed to 20M but was still only 2M

I tried rebooting my computer thinking maybe that would stop the apache server and reload the php.ini file with the correct setting, but alas that attempt also failed.

Is there any chance there could be another php.ini file that could be interfering?

The configuration file (php.ini)
is read when PHP starts up. For the server module versions of PHP,
this happens only once when the web server is started. For the
CGI and CLI versions, it happens on
every invocation.

php.ini is searched for in these locations (in order):


  • SAPI module specific location (PHPIniDir directive
    in Apache 2, -c command line option in CGI and CLI)

  • The PHPRC environment variable.

  • The location of the php.ini file
    can be set for different versions of PHP. The root of the registry keys depends on 32- or 64-bitness of the installed OS and PHP.
    For 32-bit PHP on a 32-bit OS or a 64-bit PHP on a 64-bit OS use [(HKEY_LOCAL_MACHINESOFTWAREPHP] for 32-bit version of PHP on a 64-bit OS use [HKEY_LOCAL_MACHINESOFTWAREWOW6432NodePHP]] instead.
    For same bitness installation the following registry keys
    are examined in order:
    [HKEY_LOCAL_MACHINESOFTWAREPHPx.y.z],
    [HKEY_LOCAL_MACHINESOFTWAREPHPx.y] and
    [HKEY_LOCAL_MACHINESOFTWAREPHPx], where
    x, y and z mean the PHP major, minor and release versions.
    For 32 bit versions of PHP on a 64 bit OS the following registry keys are examined in order:
    [HKEY_LOCAL_MACHINESOFTWAREWOW6421NodePHPx.y.z],
    [HKEY_LOCAL_MACHINESOFTWAREWOW6421NodePHPx.y] and
    [HKEY_LOCAL_MACHINESOFTWAREWOW6421NodePHPx], where
    x, y and z mean the PHP major, minor and release versions.
    If there is a
    value for IniFilePath in any of these keys, the first
    one found will be used as the location of the php.ini
    (Windows only).

  • [HKEY_LOCAL_MACHINESOFTWAREPHP] or
    [HKEY_LOCAL_MACHINESOFTWAREWOW6432NodePHP], value of
    IniFilePath (Windows only).

  • Current working directory (except CLI).

  • The web server’s directory (for SAPI modules), or directory of PHP
    (otherwise in Windows).

  • Windows directory (C:windows
    or C:winnt) (for Windows), or
    --with-config-file-path compile time option.

If php-SAPI.ini exists (where SAPI is the SAPI in use,
so, for example, php-cli.ini or
php-apache.ini), it is used instead of php.ini.
The SAPI name can be determined with php_sapi_name().

Note:

The Apache web server changes the directory to root at startup, causing
PHP to attempt to read php.ini from the root filesystem if it exists.

Using environment variables can be used in php.ini as shown below.

Example #1 php.ini Environment Variables

; PHP_MEMORY_LIMIT is taken from environment
memory_limit = ${PHP_MEMORY_LIMIT}

The php.ini directives handled by extensions are documented
on the respective pages of the extensions themselves. A list of
the core directives is available in the appendix. Not all
PHP directives are necessarily documented in this manual: for a complete list
of directives available in your PHP version, please read your well commented
php.ini file. Alternatively, you may find
» the latest php.ini from Git
helpful too.

Example #2 php.ini example

; any text on a line after an unquoted semicolon (;) is ignored
[php] ; section markers (text within square brackets) are also ignored
; Boolean values can be set to either:
;    true, on, yes
; or false, off, no, none
register_globals = off
track_errors = yes

; you can enclose strings in double-quotes
include_path = ".:/usr/local/lib/php"

; backslashes are treated the same as any other character
include_path = ".;c:phplib"

It is possible to refer to existing .ini variables from
within .ini files. Example: open_basedir = ${open_basedir}
":/new/dir"
.

Scan directories

It is possible to configure PHP to scan for .ini files in a directory
after reading php.ini. This can be done at compile time by setting the
–with-config-file-scan-dir option.
The scan directory can then be overridden at run time
by setting the PHP_INI_SCAN_DIR environment variable.

It is possible to scan multiple directories by separating them with the
platform-specific path separator (; on Windows, NetWare
and RISC OS; : on all other platforms; the value PHP is
using is available as the PATH_SEPARATOR constant).
If a blank directory is given in PHP_INI_SCAN_DIR, PHP
will also scan the directory given at compile time via
–with-config-file-scan-dir.

Within each directory, PHP will scan all files ending in
.ini in alphabetical order. A list of the files that
were loaded, and in what order, is available by calling
php_ini_scanned_files(), or by running PHP with the
–ini option.

Assuming PHP is configured with --with-config-file-scan-dir=/etc/php.d,
and that the path separator is :...

$ php
  PHP will load all files in /etc/php.d/*.ini as configuration files.

$ PHP_INI_SCAN_DIR=/usr/local/etc/php.d php
  PHP will load all files in /usr/local/etc/php.d/*.ini as
  configuration files.

$ PHP_INI_SCAN_DIR=:/usr/local/etc/php.d php
  PHP will load all files in /etc/php.d/*.ini, then
  /usr/local/etc/php.d/*.ini as configuration files.

$ PHP_INI_SCAN_DIR=/usr/local/etc/php.d: php
  PHP will load all files in /usr/local/etc/php.d/*.ini, then
  /etc/php.d/*.ini as configuration files.

weili

1 year ago


For someone who's also wondering.

PHP can work even if there is no configuration file(php.ini) loaded,
it will simply applies the default values to directives.


ohcc at 163 dot com

6 years ago


in php.ini you can reference to an existing directive or an environment variable using the syntax ${varname}.

Here are some examples.

sys_temp_dir = "${WINDIR}"

--- ${WINDIR} will be replaced by $_ENV['WINDIR'] at runtime

--- you can set environment variables by Apache and use them in php.ini
--- FcgidInitialEnv AUTHOR "WUXIANCHENG"
--- error_log = "${AUTHOR}.log"

error_log = "${sys_temp_dir}"

--- ${sys_temp_dir} will be replace by the value of sys_temp_dir

Also you can use PHP constants in php.ini, but DONT'T wrap them in ${} or "".

error_log = "/data/"PHP_VERSION"/"

---  it works like this php code:

$error_log =  "/data/" . PHP_VERSION . "/";


php.ini file location in ubuntuphp.ini file location.

What is the php.ini file, why we use it ? Where do I find this file on Ubuntu ? How I open and edit the php.ini file on a terminal. This is the most common questions asked by beginners who are either new to PHP or Linux.

php.ini File

The php.ini file is a default configuration file used when your PHP application runs. When PHP starts it reads the configuration setting from the php.ini file.

If you have installed LAMP on a Ubuntu operating system and unable to find and edit this file then this tutorial is for you.

PHP Script to Find php.ini Location

If you are working on  Windows, Ubuntu or any operating system. You can easily find the location of php.ini configuration file using simple PHP script.

Create a PHP file. Let’s name it inipath.php (you can choose any name with a .php extension) .

Open this file in your browser and you will get the path of  the php.ini.

php.ini file location

I am using Ubuntu and the location of php.ini in Ubuntu is /etc/php5/apache2/php.ini . Similarly, if you are running this script on Windows and Mac you’ll get the path as per their directory structure.

For version 7.4.3, the php.ini path is /etc/php/7.4/apache2/php.ini.

php.ini path on php 7

php.ini File Location in Ubuntu

For PHP5

The path of php.ini in Ubuntu is /etc/php5/apache2 . Open the terminal and start typing following commands.

$ cd  /etc/php5/apache2

$ ls

To view the files present in apache2 directory, type ls command. The files present in this directory (conf.d and php.ini) are displayed.

For PHP 7.4 version

The path of php.ini is

$ cd  /etc/php/7.4/apache2

$ ls

If you are not familiar with Linux commands then read my previous post on Linux Commands with Examples .

The other easiest way to locate the php.ini location is using locate command.

How to open & edit the php.ini configuration file on a Terminal

To open & edit the php.ini file I am using vim/vi editor.

Read more about Beginners guide for vi/vim editor.

You can directly open this file using the following command.

$  sudo vim /etc/php5/apache2/php.ini

NOTE – Once you have done the changes in the php.ini file. You need to restart the apache web server so that the new changes get reflected.

To restart the Apache WebServer.

$ sudo /etc/init.d/apache2 restart

or

$ sudo service apache2 restart

Popular PHP Articles

Abstract vs Interface in PHP

Abstract class in PHP

Programming Videos Tutorial

Conclusion

I hope this tutorial helped you to find and edit the php.ini file. If you are still facing any issue you can ask your question through comments.

Добавить комментарий