PHP Configuration (php.ini)

Ma Mahalakshmi V Updated 14 Nov 2026
5 min read ·Lesson 239 of 255

What Is php.ini?

In simple terms: php.ini is PHP's settings file. It controls how much memory a script may use, how long it may run, how large uploads can be, whether errors are shown, which time zone is used, and hundreds of other behaviors. The same PHP code can behave very differently depending on these settings, so knowing where they live and how to change them is an essential deployment skill.

Technically: When PHP starts, it reads a main php.ini file and, typically, additional .ini files from a scan directory (for example, conf.d/). Each SAPI — the command line (CLI), PHP-FPM, the Apache module — can have its own configuration. Settings (called directives) can be changed at different levels depending on their changeable mode: some only in php.ini, others per directory (.user.ini, web server configuration) or at runtime with ini_set().


Finding the Active Configuration

php --ini
Configuration File (php.ini) Path: /etc/php/8.4/cli
Loaded Configuration File:         /etc/php/8.4/cli/php.ini
Scan for additional .ini files in: /etc/php/8.4/cli/conf.d
Additional .ini files parsed:      /etc/php/8.4/cli/conf.d/10-opcache.ini,
                                   /etc/php/8.4/cli/conf.d/20-mysqlnd.ini, ...

This shows the CLI configuration. The web server's PHP-FPM uses a different file — on Debian/Ubuntu, /etc/php/8.4/fpm/php.ini. To see the configuration the web uses, check it from a web request (a protected admin page calling php_ini_loaded_file()), or run php-fpm8.4 -i | grep "Loaded Configuration".

PHP's source distribution includes two templates: php.ini-development (show errors, helpful for debugging) and php.ini-production (secure defaults). Production servers should be based on the production template.


php.ini Syntax

; Lines starting with a semicolon are comments

memory_limit = 256M          ; sizes use K, M, G
max_execution_time = 30      ; seconds
display_errors = Off         ; booleans: On/Off, 1/0, true/false, yes/no
date.timezone = "Asia/Kolkata"
error_log = /var/log/php/app-error.log

[opcache]                    ; sections are for readability (and some special cases)
opcache.enable = 1

After changing php.ini, restart the PHP process that uses it (for example, sudo systemctl restart php8.4-fpm), because PHP-FPM reads configuration only at startup. The CLI reads it every time a script starts.


Important Directives

Resources and Limits

DirectiveTypical ValuePurpose
memory_limit128M–512MMaximum memory per script (-1 = unlimited, only sensible in the CLI)
max_execution_time30Maximum script runtime in seconds for web requests (the CLI default is 0, unlimited)
max_input_time60Maximum time for parsing request data
max_input_vars1000Maximum number of input variables (protects against hash-collision attacks)
upload_max_filesize10MMaximum size of one uploaded file
post_max_size12MMaximum size of the whole request body (must exceed upload_max_filesize)
max_file_uploads20Maximum files per request

Errors and Security

DirectiveProduction ValueSee
display_errorsOffError Reporting in Production
log_errors / error_logOn / log file pathError Logging
error_reportingE_ALLError Handling
expose_phpOffHiding PHP
allow_url_includeOffFilesystem Security
open_basedir, disable_functionsAs neededFilesystem Security
session.* (cookie_secure, cookie_httponly, use_strict_mode, …)HardenedSession Security

Locale and Performance

DirectivePurpose
date.timezoneDefault time zone (see Timezones)
default_charsetUTF-8 (the default)
opcache.*Bytecode caching — essential for production speed (see OPcache & Performance)
realpath_cache_size, realpath_cache_ttlCaching of resolved file paths, helpful for large applications

Reading and Changing Settings at Runtime

<?php
echo "memory_limit: " . ini_get('memory_limit') . "\n";
echo "max_execution_time: " . ini_get('max_execution_time') . "\n";

$old = ini_set('max_execution_time', '60');
var_dump($old);
echo "max_execution_time now: " . ini_get('max_execution_time') . "\n";

var_dump(ini_set('expose_php', '0'));

Output (command line)

memory_limit: 128M
max_execution_time: 0
string(1) "0"
max_execution_time now: 60
bool(false)

How It Works

  1. ini_get() returns a setting's current value as a string — exactly as configured (128M, not a number of bytes).
  2. ini_set() changes a setting for the current script only and returns the previous value.
  3. expose_php cannot be changed at runtime, so ini_set() returns false.

Changeable Modes

ModeWhere the Directive Can Be SetExamples
PHP_INI_ALLAnywhere, including ini_set()memory_limit, max_execution_time, display_errors, date.timezone
PHP_INI_PERDIRphp.ini, .user.ini, web server config — not ini_set()upload_max_filesize, post_max_size, short_open_tag
PHP_INI_SYSTEMphp.ini or the server configuration onlyexpose_php, disable_functions, opcache.memory_consumption

upload_max_filesize and post_max_size are evaluated before your script runs (while PHP reads the request), which is why changing them with ini_set() is impossible.

Converting Size Values

Values such as 256M must be converted before numeric comparisons:

<?php
function iniBytes(string $value): int
{
    $value = trim($value);
    $number = (int) $value;

    return match (strtoupper(substr($value, -1))) {
        'G' => $number * 1024 ** 3,
        'M' => $number * 1024 ** 2,
        'K' => $number * 1024,
        default => $number,
    };
}

echo iniBytes('256M') . "\n";
echo iniBytes('2G') . "\n";

Output

268435456
2147483648

PHP 8.2 added ini_parse_quantity(), which performs this conversion natively: ini_parse_quantity('256M') returns 268435456.


Per-Directory and Per-Pool Configuration

MethodApplies ToExample
.user.ini in a directoryPHP-FPM/CGI requests for scripts in that directory treeupload_max_filesize = 20M
PHP-FPM pool configurationAll requests handled by a poolphp_admin_value[memory_limit] = 256M
Apache (mod_php)Directories/virtual hostsphp_value memory_limit 256M

php_admin_value in an FPM pool cannot be overridden by .user.ini or ini_set() — useful for enforcing limits on shared servers. .user.ini files are re-read periodically (user_ini.cache_ttl, 300 seconds by default).


Common Mistakes

Editing the Wrong php.ini

Effect: Changes to the CLI's file do not affect the website (or vice versa).

Fix: Check the loaded file for each SAPI; restart PHP-FPM after changes.

post_max_size Smaller Than upload_max_filesize

Effect: Large uploads fail with empty $_POST and $_FILES.

Fix: Keep post_max_size larger than the maximum upload size plus form data.

Using ini_set() for Directives It Cannot Change

Effect: The change silently fails (false is returned).

Fix: Check the directive's changeable mode; set it in php.ini or the server configuration.

Unlimited Resources in Web Requests

Effect: Runaway scripts exhaust server memory or workers.

Fix: Keep memory_limit and max_execution_time bounded for web requests; raise them only for specific CLI jobs.


Best Practices

  • Base production configuration on php.ini-production and keep it under version control (or configuration management).
  • Know which php.ini each SAPI loads, and restart PHP-FPM after changes.
  • Set limits deliberately: memory, execution time, uploads, and input variables.
  • Use ini_set() only for PHP_INI_ALL directives that genuinely vary per script.
  • Enforce critical settings with php_admin_value in FPM pools on shared servers.

Official reference: https://www.php.net/manual/en/configuration.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about PHP Configuration (php.ini) and get answers drawn from it.

Signed-in readers only.