Как найти php ini на сервере

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 . "/";


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.

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?

In this tutorial, we’re going to discuss php.ini—the main configuration file in PHP. From the beginner’s perspective, we’ll discuss what it’s meant for, where to locate it, and a couple of important configuration settings it provides.

What Is php.ini?

Whether you’re a PHP beginner or a seasoned developer, I’m sure that you’ve heard of php.ini: the most important PHP configuration file. 

When PHP is run, it looks for the php.ini file in some specific locations and loads it. This file allows you to configure a few important settings that you should be aware of. Quite often, you’ll find you need to tweak settings in the php.ini file.

On the other hand, it’s certainly possible that you’ve never needed to modify php.ini. PHP can run happily with the settings provided in the default php.ini file, since PHP ships with these default recommended settings. In fact, there are no critical configuration parameters that you must set in order to run PHP. 

However, the php.ini file provides a couple of important settings that you want to make yourself familiar with. In fact, as a PHP developer, it’s inevitable, and you’ll encounter it sooner rather than later.

Where Is php.ini?

In this section, we’ll see how to find the php.ini file which is loaded when you run the PHP script. This can be tricky—the location of the php.ini file vastly varies by the environment you’re running PHP with. If you’re running Windows, you’ll likely find the php.ini file within the directory of your PHP installation in the system drive. On the other hand, if you’re running another operating system, then it’s difficult to guess the exact location of the php.ini file—there are several possibilities.

This is where the phpinfo() function comes to the rescue. It will tell you where php.ini is located, and it will also output all the important PHP configuration information. 

You can run phpinfo() by creating a .php file and calling that function. Go ahead and create the phpinfo.php file with the following contents and place it in your document root:

1
<?php
2
phpinfo();
3
?>

Load this file in your browser, and you should see the output of phpinfo(). Look for the following section.

LocationLocationLocation

As you can see, there are two sections. The first one, Configuration File (php.ini) Path, indicates the default path of the php.ini file in your system. And the second one, Loaded Configuration File, is the path from where the php.ini file is being loaded when PHP is run.

So you can edit the php.ini file indicated in the Loaded Configuration File section, and that should work in most cases. Of course, if you’re running PHP as an Apache module, you need to restart the Apache server to make sure that the changes you’ve made in the php.ini file are reflected.

On the other hand, if you’re using software like WAMP or XAMPP to run your web development stack, it’s even easier to modify the php.ini file—you can directly access it via the WAMP or XAMPP UI.

In the next section, we’ll explore a couple of important settings in the php.ini file.

Important Settings in php.ini

The php.ini file provides a lot of configuration directives that allow you to modify various behaviors of PHP. In fact, when you open the php.ini file, you may get overwhelmed by the number of directives it provides. I’ll try to group them based on their behavior, and I hope it’ll be easy for you to understand.

Of course, we won’t go through each and every directive, but I’ll try to cover the most important ones. Let’s have a look at the types of directives that we’re going to discuss.

  • error handling directives
  • file upload directives
  • security related directives
  • session directives
  • miscellaneous directives

Error Handling Directives

In this section, we’ll go through directives that are related to error handling and are useful for debugging during development.

display_errors

The display_errors directive allows you to control whether errors are displayed on the screen during script execution. You can set it to On if you want errors to be displayed on the screen and Off if you want to disable it. It’s important that you don’t ever enable this on a production site—it will slow your site down and could give hackers valuable clues to your site’s security vulnerabilities.

error_reporting

This directive allows you to set the error reporting level. Mostly, this directive works in conjunction with the display_errors directive. This directive can accept E_ALL, E_NOTICE, E_STRICT, and E_DEPRECATED constants.

You can set it to E_ALL if you want to display all types of errors like fatal errors, warnings, deprecated functions, etc. You can also combine the different values if you want to filter out specific errors. For example, if you want to display all errors except notices, you can set it to E_ALL & ~E_NOTICE.

error_log

On a production website, you need to make sure that PHP doesn’t display any errors to the client browser. Instead, you can log errors somewhere so that later on you can refer to them if something goes wrong with your site. The error_log directive allows you to set the name of the file where errors will be logged. You need to make sure that this file is writable by the web server user.

File Upload Directives

In this section, we’ll see a couple of important directives that allow you to enable file uploading capabilities in your PHP forms.

file_uploads

This is a boolean directive which allows you to enable HTTP file uploads. If you set it to On, you can use the file field in your forms and users will be able to upload files from their computer. On the other hand, if you set it to Off, file uploading is disabled altogether.

upload_max_filesize

If you have enabled the file upload feature on your website and you’re facing difficulties in uploading files, this is the directive you should check first. It allows you to set the maximum size of a file that can be uploaded.

By default, it’s set to 2MB, and thus users can’t upload files larger than 2MB. You can fine-tune this value as per your requirements—often you’ll want to increase this limit to allow larger file uploads.

post_max_size

This setting allows you to set the maximum size of the POST data in your forms. When a user submits a form with the POST method, the total POST data size should not exceed the value you’ve set in this directive.

This should be larger than the value you’ve set in the upload_max_filesize directive, since file uploads are handled with POST requests.

Security Directives

In this section, we’ll see a few important directives that are related to security.

allow_url_fopen

The allow_url_fopen directive is disabled by default. But when it’s enabled, it allows remote file inclusion in PHP file functions. This means that your PHP files can include code from other servers. Be wary about enabling this—if your code is subject to an injection attack, remote file inclusion will make it much easier for a malicious user to hijack your server.

allow_url_include

The allow_url_include directive is similar to the allow_url_fopen directive, but it enables remote file inclusion in include functions. It allows you to include remote files in the include, include_once, require, and require_once functions.

If you want to enable this directive, you need to make sure that you’ve enabled the allow_url_fopen directive as well.

Session Directives

Session management is one of the most important aspects when you’re working with PHP. In this section, we’ll go through a couple of important session directives.

session.name

The session.name directive allows you to set the name of the session cookie. By default, it is set to PHPSESSID, but you can change it to something else by using this directive.

session.auto_start

If you set the value of the session.auto_start directive to 1, the session module in PHP starts a session automatically on every request, and thus you don’t have to use the session_start function in your scripts.

session.cookie_lifetime

The session.cookie_lifetime directive allows you to set the lifetime of a session cookie. By default, it is set to 0 seconds, and it means that the session cookie is deleted when the browser is closed. This is a really useful setting which allows you to set up a «remember me» kind of functionality, allowing your users to pick up where they left off on your site.

Miscellaneous Directives

In this last section, we’ll see a couple of other directives that are important in the context of PHP script execution.

memory_limit

The memory_limit directive allows you to limit the maximum amount of memory a script is allowed to use.

You want to fine-tune this directive as per your requirements, and you should not set this too high to avoid memory outages on your server—poorly written or buggy scripts can eat up all the memory on your server if you let them!

max_execution_time

The max_execution_time directive sets the maximum amount of time a script is allowed to run before it is terminated. The default is 30 seconds, and you can increase it to a reasonable limit as per your requirements if you need to.

Similar to the memory_limit directive, you should not set this too high to avoid issues on your server.

max_input_time

The max_input_time directive allows you to set the maximum amount of time a script is allowed to parse incoming form data from a GET or POST.

If you have forms on your website that submit a large amount of data, you might like to increase the value of this directive.

Conclusion

It’s impossible to cover each and every directive within a single article, but I’ve tried to cover the important ones. Feel free to post your queries if you want to know about any specific directives, and I’ll be happy to help!

As a PHP developer, it’s important that you understand the different directives in the php.ini file, and that should help you to fine-tune your PHP configuration to your requirements.

The Best PHP Scripts on CodeCanyon

Explore thousands of the best and most useful PHP scripts ever created on CodeCanyon. With a low-cost one-time payment, you can purchase these high-quality WordPress themes and improve your website experience for you and your visitors.

Here are a few of the best-selling and up-and-coming PHP scripts available on CodeCanyon for 2020.

Did you find this post useful?

Sajal Soni

Software Engineer, FSPL, India

I’m a software engineer by profession, and I’ve done my engineering in computer science. It’s been around 14 years I’ve been working in the field of website development and open-source technologies.

Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I’ve worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I’ve also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e-commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce.

I also like to attend community tech conferences, and as a part of that, I attended the 2016 Joomla World Conference held in Bangalore (India) and 2018 DrupalCon which was held in Mumbai (India). Apart from this, I like to travel, explore new places, and listen to music!

  1. Введение
  2. Причины для поиска php.ini
  3. Как найти данный файл
  4. Ищем файл настроек PHP в популярных CMS
  5. Расположение php.ini в ОС Linux разных версий и сборок
  6. Как настроить php.ini под свои потребности?

Работа с файлами сайта, размещенного на хостинге или собственной виртуальной машине, рано или поздно приведет вас к файлу основных настроек языка PHP. Узнать, где лежит php ini, можно несколькими способами, которые зависят от операционной системы. Если вы уже используете хостинг на Windows или Linux, информация по поиску и использованию данного файла вам пригодится.

Расположение файла редко зависит от того, какой конструктор сайтов или оболочку вы используете. Вордпресс, Джумла и другие оболочки будут использовать стандартный php.ini, доступный в ОС сервера, либо тот, что поставляется вместе с инструментарием Denver.

Причины для поиска php.ini

Изменения в php.ini для сайта производятся тогда, когда нужно расширить или снять ограничения на некоторые операции – например, объем импортируемых или экспортируемых данных. Снятие ограничений полезно, когда вы переносите сайт вместе с его содержимым с одной платформы на другую, так как настройки по умолчанию могут этому помешать. Продвинутые пользователи могут настроить здесь все, что связано с исполнением команд на языке PHP.

Как найти данный файл

Первый шаг в поисках подойдет для случая, когда сайт уже запущен на виртуальной машине или хостинге (или вы как раз собираетесь это сделать). Создайте в корневой папке сайта файл с расширением PHP, куда скопируйте следующий простой код:


<?php
phpinfo();
?>

Выполнение этого кода при открытии файла-страницы на сайте даст весьма подробную информацию об используемой версии PHP для вашего сайта, а также другие важные параметры. Там же будет и расположение файла php.ini на хостинге, которое используется в данный момент.

Основное правило при использовании Apache, Denver и других оболочек для виртуального сервера: вы фактически работаете с тем же Linux’ом, поэтому пути находятся стандартными для этой системы (и для самого PHP) способами, и, скорее всего, содержат соответствующие названия в именах папок. Если советы, касающиеся конкретных CMS, не помогли, просто ищите файл стандартным способом через создание страницы с phpinfo().

Ищем файл настроек PHP в популярных CMS

Даже пользователю-новичку может быть нужно найти, где находится php ini в WordPress или Joomla. Эти CMS дружелюбны к новым пользователям, но изменения параметров PHP все равно могут потребоваться по разным причинам. Файл обычно располагается в usrlocalphp5 относительно корневой папки, которую вам предоставляет хостинг, или папки, которая является рабочей для вашего внутреннего сервера. Метод с созданием проверочного файла, описанный выше, отлично работает в этом случае. Сами CMS обычно не вносят изменения в расположение php ini.

Будьте внимательны, когда заказываете хостинг веб сайтов – в некоторых случаях провайдер может ограничить или запретить изменение важных файлов, в том числе конфигурационных файлов PHP. Если возникают проблемы с поиском или открытием файла, есть смысл обратиться в техподдержку хостинга напрямую и уточнить, какие возможности вам доступны. В работе с собственным виртуальным сервером на Denver/Apache вас никто не ограничивает.

Если вы работаете в CMS Bitrix, вы можете и не найти файл настроек PHP в привычных директориях. Файл php ini в Bitrix лежит в разных папках в зависимости от версии самого Битрикса, поэтому создавайте тестовую страничку из первого примера и узнавайте точный путь оттуда. На некоторых хостингах вы можете найти путь /home/login, но туда обычно загружаются собственноручно созданные файлы, исходник для которых берется из /home/login/etc.

Расположение php.ini в ОС Linux разных версий и сборок

ОС Linux считается самой подходящей системой для регулярной работы с хостингом, сайтами на PHP и сопутствующими процессами. Если вы имеете непосредственный доступ к файловой системе сервера (являетесь его владельцем, например), то ищите php.ini по адресам /etc/, /usr/local/lib или /usr/local/php/etc/ – это самые распространенные места. PHP Zend размещает ини файл в /usr/local/Zend/etc/, учтите это, если используете данную оболочку. Вы можете задать и обычный поиск файла в системе, но так вы не узнаете, какой из нескольких файлов php.ini реально используется в данный момент для задания настроек сервера и сайта.

Вряд ли сложным исключением станет сборка ОС на базе Ubuntu. Место, где лежит php.ini в Ubuntu, определяется через phpinfo() и зависит от того, какой именно тип сервера вы используете. Для Apache это может быть /etc/php5/apache2, например. Если файл вовсе не удается обнаружить, то его можно создать вручную или скопировать из другого места, но только если знаете примерную структуру файла.

Как настроить php.ini под свои потребности?

Настройка важных и второстепенных параметров может быть весьма долгим процессом. Если у вас есть выделенный веб сервер, и вы хотите тонко настроить его работу, то рекомендуем обратиться к одному из онлайн руководств по параметрам в PHP.ini для продвинутых пользователей. Сам процесс задания параметров сводится к изменению числовых или текстовых значений для одной из строк-директив.

Вот некоторые из настроек, которые можно изменить, если владелец хостинга разрешает использовать php.ini и редактировать его самостоятельно:

post_max_size

upload_max_filesize

Эти две строки важны для любого пользователя, желающего снять ограничение на объем загружаемых файлов. Эта настройка проверяется при импорте записей в Вордпресс и другие CMS того же типа, значения по умолчанию в целях безопасности сервера сделаны очень скромными. Если вы точно знаете, что делаете, можете значительно увеличить лимит, либо просто подогнать его под размер импортируемых файлов (если уже знаете их примерный объем).

max_execution_time

max_input_time

Здесь задается максимальное время в секундах, которое отводится на выполнение каждого скрипта и загрузку данных в процессе его работы соответственно.

memory_limit = 16M

Эта важная директива задает максимальное выделение памяти под один отдельный скрипт. Не завышайте это значение, если не знаете, для чего это может понадобиться. Скрипты PHP достаточно легковесны с точки зрения обычного пользователя.

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

Понравилась статья? Поделить с друзьями:
  • Как найти ключевые слова в курсовой
  • Как найти дельта м ядра
  • Как составить претензию за неуплату оказанных услуг
  • Как найти темнокожего парня
  • Как составить совет на английском