Here’s a Bash script that can help optimize and secure PHP for WordPress on Linux (Tested on CentOS 8 and 9). The script will also discover the server specifications to optimize the results. Each section of the code is commented to explain what it does. Please note that this script assumes you have root access to the server.
Bash Script to Optimize and Secure PHP
#!/bin/bash
# Discover server specifications
cpu_cores=$(grep -c '^processor' /proc/cpuinfo)
memory=$(awk '/MemTotal/ { print $2 }' /proc/meminfo)
# Set PHP configuration file paths
php_ini_path="/etc/php.ini"
php_fpm_pool_conf="/etc/php-fpm.d/www.conf"
# Backup original PHP configuration files
cp $php_ini_path $php_ini_path.backup
cp $php_fpm_pool_conf $php_fpm_pool_conf.backup
# Configure PHP settings for WordPress optimization
# Enable OPcache
sed -i 's/;opcache.enable=0/opcache.enable=1/' $php_ini_path
sed -i 's/;opcache.enable_cli=0/opcache.enable_cli=1/' $php_ini_path
# Adjust OPcache settings based on server specifications
opcache_memory=$((memory / 8 / 1024))M
sed -i "s/opcache.memory_consumption=.*/opcache.memory_consumption=$opcache_memory/" $php_ini_path
# Set the number of PHP-FPM child processes based on CPU cores
sed -i "s/pm.max_children = .*/pm.max_children = $(($cpu_cores * 2 + 1))/" $php_fpm_pool_conf
# Configure PHP-FPM settings for WordPress optimization
# Set PHP-FPM process manager to ondemand
sed -i 's/pm = .*/pm = ondemand/' $php_fpm_pool_conf
# Restart PHP-FPM for the changes to take effect
systemctl restart php-fpm
# Secure PHP configuration
# Disable dangerous PHP functions
sed -i 's/disable_functions = .*/disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source,eval/' $php_ini_path
# Limit PHP maximum execution time
sed -i 's/max_execution_time = .*/max_execution_time = 30/' $php_ini_path
# Enable PHP-FPM slow log
sed -i 's/;request_slowlog_timeout = .*/request_slowlog_timeout = 10s/' $php_fpm_pool_conf
sed -i 's/;slowlog = .*/slowlog = \/var\/log\/php-fpm\/slow.log/' $php_fpm_pool_conf
# Restart PHP-FPM for the changes to take effect
systemctl restart php-fpm
# Print optimization completion message
echo "PHP optimization for WordPress completed."
Make sure to run the script with root privileges using the sudo
command. After executing the script, PHP will be optimized for WordPress with improved performance based on the server specifications. The original PHP configuration files will be backed up, and the optimized settings will be applied.
Note: Before running any script that modifies critical configuration files, it is always recommended to have a backup of those files and test the changes on a non-production environment.
Related Articles