Introduction
Optimizing your php.ini
file is crucial for improving the performance and security of your PHP applications. This tutorial will guide you through the best practices for configuring php.ini
, PHP’s primary configuration file.
Setting PHP Directives
Directives in the php.ini
file control how PHP behaves. Let’s cover some key settings.
error_reporting = E_ALL
Using E_ALL
is recommended during development to catch all potential errors.
display_errors = On
log_errors = On
error_log = "/var/log/php_errors.log"
This combination ensures that while developers see errors, they’re also logged for later review. In production, set display_errors
to Off
.
Memory and Execution Limits
Managing memory and execution time can prevent scripts from exhausting resources:
memory_limit = 128M
max_execution_time = 30
These limits protect your server from individual scripts using too much memory or taking too long to execute.
File Uploads
Control the size and handling of file uploads:
file_uploads = On
upload_max_filesize = 20M
post_max_size = 25M
Keep post_max_size
larger than upload_max_filesize
to account for additional POST data.
Performance Tweaks
Use opcode caching with OPcache:
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.validate_timestamps=2
Adjust these values based on your server’s resources and application requirements.
Session Handling
Configuring sessions correctly can enhance security:
session.cookie_secure = On
session.use_only_cookies = On
session.cookie_httponly = On
session.sid_length = 40
These settings help protect session cookies from hijacking and XSS attacks.
Date and Time
Ensure your scripts use the correct time zone:
date.timezone = "Europe/Lisbon"
Choose the timezone appropriate for your server’s location.
Database Connections
Tweaking PHP’s PDO and MySQLi settings can improve interaction with databases:
pdo_mysql.default_socket="/var/run/mysqld/mysqld.sock"
mysqli.reconnect = On
Be mindful of the default_socket
directive, and enable mysqli.reconnect
for persistent DB connections.
Error Handling for Production
In production environments, tighten security and reduce error verbosity:
display_errors = Off
expose_php = Off
log_errors = On
This hides PHP errors from users and reduces server exposure information.
Handling Paths and Directories
Configuring include paths can minimize file system overhead:
include_path = ".:/usr/share/php"
Customize the path based on frequently accessed directories to speed up file includes.
Conclusion
Effectively configuring php.ini
can dramatically improve your PHP application’s performance and security. While the above directives serve as a strong starting point, always tailor settings to match the specific demands of your web application and server environment.