php change php ini
How to change php.ini by PHP?
EDIT
5 Answers 5
If you are using PHP 5.3 short_open_tag is no longer an option.
Short tags have been deprecated as of PHP 5.3 and may be removed in PHP 6.0.
Yes, ini_set() is what you want.
EDIT: Added an example
Although you can use ini_set, be careful (quoted from the PHP Documentation)
Not all the available options can be changed using ini_set(). There is a list of all available options in the appendix.
If you are changing options like magic_quotes, short_open_tags, that’s OK. But if you are going to change safe_mode, enable_dl, etc. you might face certain problems.
if you want to change it during a session and forget about it later, use ini_get() and ini_set(). If you want to actually modify php.ini programmatically, you can parse the ini file using parse_ini_file, change your options and rewrite back to disk. See here for more
or you can write your own string replacement routine using the normal opening of file, preg_replace() etc..
Please edit php.ini file
Not the answer you’re looking for? Browse other questions tagged php or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Изменения конфигурации PHP с помощью php.ini и phpinfo()
phpinfo(): получить информацию о PHP
Функция phpinfo() проста в использовании. Создайте PHP-файл на своем сервере и разместите в нем вызов этой функции:
Затем заходите на эту страницу через браузер. И все.
Много информации
Настройка PHP: Как работает php.ini
Подобные файлы очень похожи. Они включают в себя ряд значений, установленных в строках. Например:
Что отличает хороший INI-файл от плохого, так это то, насколько полезны и понятны комментарии. В этом отношении php.ini отличается в лучшую сторону. В нем содержится множество комментариев, которые помогут разобраться, прежде чем устанавливать значения:
Значения параметров конфигурации PHP, полезные для WordPress разработчиков
Примечания относительно редакторов, прав доступа и перезагрузки сервера
php.ini — это файл конфигурации, и поскольку он часто размещается на сервере, можно столкнуться с несколькими проблемами. Например, отсутствие доступа к файлу с помощью обычных удобных инструментов или возможности сохранить внесенные изменения:
Открытие без sudo приводит к выводу предупреждения о запрете на запись и невозможности сохранить изменения
Для редактирования nano — лучший текстовый редактор. Все его горячие сочетания клавиш прописаны на экране. Поэтому я часто редактирую файл php.ini на удаленном сервере с помощью команды:
Конфигурация с помощью php.ini и phpinfo()
Пожалуйста, опубликуйте ваши комментарии по текущей теме статьи. За комментарии, дизлайки, отклики, подписки, лайки огромное вам спасибо!
Php change php ini
Представленные здесь значения по умолчанию используются в случае, если не был подключён php.ini ; значения для боевого php.ini и для разработки могут различаться.
Языковые опции
Имя | По умолчанию | Место изменения | Список изменений |
---|---|---|---|
short_open_tag | «1» | PHP_INI_PERDIR | |
precision | «14» | PHP_INI_ALL | |
serialize_precision | «-1» | PHP_INI_ALL | До версии PHP 7.1.0 значение по умолчанию было равно 17. |
disable_functions | «» | Только PHP_INI_SYSTEM | |
disable_classes | «» | Только php.ini | |
exit_on_timeout | «» | PHP_INI_ALL | |
expose_php | «1» | Только php.ini | |
hard_timeout | «2» | PHP_INI_SYSTEM | Доступна с версии PHP 7.1.0. |
zend.exception_ignore_args | «0» | PHP_INI_ALL | Доступна с версии PHP 7.4.0 |
zend.multibyte | «0» | PHP_INI_ALL | |
zend.script_encoding | NULL | PHP_INI_ALL | |
zend.detect_unicode | NULL | PHP_INI_ALL | |
zend.signal_check | «0» | PHP_INI_SYSTEM | |
zend.assertions | «1» | PHP_INI_ALL с ограничениями |
Краткое разъяснение конфигурационных директив.
Выдаёт факт присутствия PHP на сервере, включая передачу версии PHP в HTTP-заголовке (например, X-Powered-By: PHP/5.3.7).
Эта директива позволяет отключить некоторые функции. Она принимает список имён функций, разделённый запятыми.
Только внутренние функции могут быть отключены с помощью этой директивы. Пользовательские функции ей не подвержены.
Если процесс стартован в режиме релиза, zend.assertions не может быть изменён во время выполнения, так как код утверждений не генерируется.
Когда истечёт время ожидания, установленное в max_execution_time, среда выполнения PHP аккуратно отключит ресурсы. Если во время этого что-то застрянет, время ожидания будет установлено на указанное количество секунд. Когда истечёт жёсткое время ожидания, PHP завершит работу с ошибкой. Если установлено значение 0, жёсткое время ожидания никогда не активируется.
Когда PHP останавливается после жёсткого времени ожидания, это будет выглядеть примерно так:
Исключает аргументы из трассировки стека, сгенерированных из исключений.
Разрешает парсинг исходных файлов в многобайтных кодировках. Включение zend.multibyte требуется для использования кодировок символов подобных SJIS, BIG5 и т.д., содержащих специальные символы в многобайтных строковых данных. Совместимые с ISO-8859-1 кодировки, например UTF-8, EUC и т.д., не требуют эту опцию.
Модуль zend.multibyte требует установленного модуля «mbstring».
Данное значение будет использовано, только при отсутствии директивы declare(encoding=. ) в начале скрипта. При использовании кодировок несовместимых с ISO-8859-1, нужно использовать опции и zend.multibyte и zend.script_encoding.
Определяет, нужно ли проверять заменённые обработчики сигналов при завершении скрипта.
Эта директива только для Apache1 mod_php, которая заставляет потомка Apache завершиться, если произошёл тайм-аут исполнения скрипта PHP. Такой тайм-аут приводит к внутреннему вызову longjmp() в Apache1, который оставляет некоторые модули в несогласованном состоянии. По завершении процесса все неснятые блокировки или память будут очищены.
Ограничения ресурсов
Имя | По умолчанию | Место изменения | Список изменений |
---|---|---|---|
memory_limit | «128M» | PHP_INI_ALL |
Краткое разъяснение конфигурационных директив.
Настройка производительности
Имя | По умолчанию | Место изменения | Список изменений |
---|---|---|---|
realpath_cache_size | «4M» | PHP_INI_SYSTEM | До PHP 7.0.16 и 7.1.2, по умолчанию было «16K» |
realpath_cache_ttl | «120» | PHP_INI_SYSTEM |
Использование open_basedir отключит кеш realpath.
Краткое разъяснение конфигурационных директив.
Определяет размера кеша realpath, используемого в PHP. Это значение должно быть увеличено на системах, в которых PHP открывает большое количество файлов соответственно количеству выполняемых файловых операций.
Размер равный общему числу байт, хранящимся в строках путей, плюс размер данных связанных с кешируемым элементом. Это значит, что для хранения длинных путей в кеше, размер этого кеша должен быть больше. Это значение не определяет напрямую количество разных путей, которые могут быть закешированы.
Размер, необходимый для кеширования, зависит от системы.
Время (в секундах) в течение которого будет использован кеш realpath для указанного файла или директории. Для систем с редко меняющимися файлами это значение можно увеличить.
Обработка данных
Имя | По умолчанию | Место изменения | Список изменений |
---|---|---|---|
arg_separator.output | «&» | PHP_INI_ALL | |
arg_separator.input | «&» | PHP_INI_PERDIR | |
variables_order | «EGPCS» | PHP_INI_PERDIR | |
request_order | «» | PHP_INI_PERDIR | |
auto_globals_jit | «1» | PHP_INI_PERDIR | |
register_argc_argv | «1» | PHP_INI_PERDIR | |
enable_post_data_reading | «1» | PHP_INI_PERDIR | |
post_max_size | «8M» | PHP_INI_PERDIR | |
auto_prepend_file | NULL | PHP_INI_PERDIR | |
auto_append_file | NULL | PHP_INI_PERDIR | |
default_mimetype | «text/html» | PHP_INI_ALL | |
default_charset | «UTF-8» | PHP_INI_ALL | |
input_encoding | «» | PHP_INI_ALL | |
output_encoding | «» | PHP_INI_ALL | |
internal_encoding | «» | PHP_INI_ALL |
Краткое разъяснение конфигурационных директив.
Этот разделитель используется в генерируемых PHP URL в качестве разделителя аргументов.
Список разделителей, используемых PHP для получения переменных из URL.
Каждый символ в этой директиве считается разделителем!
Эта директива регулирует порядок, в котором PHP добавляет переменные GET, POST и Cookie в массив _REQUEST. Добавление производится слева направо, новые значения перезаписывают старые.
Когда включено, переменные SERVER, REQUEST и ENV создаются в тот момент, когда они впервые используются (Just In Time), а не в начале выполнения скрипта. Если эти переменные в скрипте не используются, включение этой директивы приведёт к росту производительности.
Использование переменных SERVER, REQUEST и ENV проверяется на стадии компиляции, поэтому их использование с помощью, например, переменных переменных не запустит их инициализацию.
Changing PHP Settings in a php.ini File
For Linux Web Hosting and Managed Dedicated Server packages
In this article, we’ll show you how to change the PHP settings for your webspace. You can set individual PHP settings, such as different security settings or file limits, for each of your applications.
What is php.ini?
Example Contents of a php.ini File
The statements must be entered in the php.ini line by line according to the following scheme:
Name of the Directive = Assigned Value
For an overview of the changeable settings (php.ini directives), see the article Which PHP settings can I change?
Creating a php.ini File
Upload the Edited php.ini File to Your Webspace
After you have created the php.ini file, you have to upload it to the directory where your PHP script is located:
Please note: If the configuration change is intended to apply to scripts located in different directories, the php.ini file must be uploaded to each directory. If your web hosting package has SSH access, you can easily do this with a small shell script. How to do this is shown in the article Apply PHP settings to all subdirectories.
Check the Results
You can check whether the desired setting is active with a small PHP program.
Hint: The output of the info script is very extensive. Therefore, use the search function of your browser to find the line with the desired information. The search function is usually accessed using the key combination [CTRL]+[F] for Windows or [CMD]+[F] for macOS.
Serious about WordPress development?
Check out our awesome premium courses!
PHP Configuration Changes with php.ini and phpinfo()
If you do enough WordPress development, you’ll eventually find yourself in need of some PHP environment changes. These’ll look slightly different depending on circumstance, but you’ll have an issue that requires you change the way PHP behaves. Maybe you need to extend the execution time for long-running script that you really must run. Maybe you need to increase the upload limit because a client insists they let their team upload 500 megabyte PDFs.
Whatever it is, you’ll need to have some familiarity with the php.ini file to make the changes. And while it’s a pretty straight-forward file, there are some useful tips you should know about it. If you’re making those changes, another great tool to have in you back pocket is the phpinfo() function. While you probably shouldn’t expose the output of this command on a production server, access to it is a hugely valuable when doing a lot of little things. One of the most common: finding the php.ini file you need to change.
phpinfo() : Get Info About PHP
phpinfo() is really easy to use. What do you do? You create a PHP file on your server — I frequently call it info.php but it doesn’t matter the name — and you put that function call into it. That’s all. The net result is a file with about these contents:
Then you visit that page in your web browser. That’s it.
A LOT of Information
If there’s a problem beginners face with phpinfo it’s not that it’s hard to get working. It’s that it’s an incredibly large amount of information, much of which will make little or no sense. But all that information is exactly what makes it hugely valuable to someone with the stomach to not get intimidated and some facility with their browser’s ability to search a page.
PHP Configuration: What and Why of php.ini
These files are all pretty similar. They’ll have a number of values set in lines that are going to look pretty familiar to any programmer, like:
What sets a good INI file apart from a bad one is how useful and clear the comments are. A php.ini rolled out with default values is pretty solid in that regard. Rather than looking quite like the above, you’ll see lots of comments as preamble before a value is set. So rather than simply declaring the memory_limit as it did above, you’ll see explanations before values, like:
As you may have guessed, in a php.ini anything after a semicolon (;) isn’t parsed, and is simply treated as a comment. You’ll also see declarations, similar to the memory_limit line, commented out. When a value isn’t provided, either because it is deleted or commented out, PHP uses a default value.
PHP Config Values That Are Useful For WordPress Devs
There are a relatively small number of values inside of the php.ini file that you’ll ever need to edit as a WordPress developer (or even as an average non-WordPress PHP developer).
Final Notes on Editors, File Permissions, Server Restarts
Because php.ini is a configuration file, and because it’s often on a server, you may hit a couple issues: you’ll not have easy access to the file via your usual comfortable tools, when you’ve edited the file you may not be able to save your changes, or the changes you made may seem to have no effect.
Opened without sudo lead to warning of no write permission and the inability to save your changes… 🙁
For editing, when you’re new to the terminal and SSHing into a box for the first time: nano is the best text editor. All of its keyboard shortcuts are clearly spelled out on the screen. (^ is the CTRL key…) It’s still really the only command-line text editor I use, because I rarely need one and it’s got just enough features to keep me satisfied. So I often edit my php.ini on a remote server with a command like:
Finally, you *may* need to restart your server or the FastCGI daemon. Whether or not that’s absolutely required depends on some of the subtleties of how exactly our server is configured. If you’re making changes and it’s not having an effect — you’ll know with your phpinfo page — and you’re on a server where you have the power to restart (not shared hosting), you may need to. The specific command for that vary a fair amount on server configuration and operating system, however, so I’ll leave you to Google for them.