PHP Security: Limit Resources Used By Script

How do I control and put limits on php scripts such as maximum execution time of each script and upload file size?

PHP supports the following resource limits directives in php.ini file:

  1. max_execution_time : Maximum execution time of each script, in seconds.
  2. max_input_time : Maximum amount of time each script may spend parsing request data.
  3. memory_limit : Maximum amount of memory a script may consume.

Edit /etc/php.ini or /etc/php/7.0/fpm/php.ini (fpm-php 7 config), enter:
# vi /etc/php.ini
# vi /etc/php/7.0/fpm/php.ini
Set up values as follows:

max_execution_time =  30
max_input_time = 30
memory_limit = 40M

Set maximum size of POST data that PHP will accept:

post_max_size = 8M

Set maximum allowed size for uploaded files:

upload_max_filesize = 2M

Turn on or off HTTP file uploads (disallow uploading unless necessary):

file_uploads = Off

Make sure PHP redirects appropriately with the following:

cgi.force_redirect = 0

Disable file requests as fopen calls with the following

allow_url_fopen = Off

Turn on SQL safe mode:

sql.safe_mode = On

If you set sql.safe_mode, you need to set the following too:
mysqli.default_host = ""
mysqli.default_port = "3306"
mysqli.default_user = "userNameHere"
mysqli.default_pw = "PasswordHere"

Now your Perl/Php/Python scripts can directly connect to the database without passing host,user and password information. Next, reload Apache web server:
# service httpd reload
Reload lighttpd web server:
# /etc/init.d/lighttpd reload
OR reload php7.0-fpm:
# /etc/init.d/php7.0-fpm reload
OR use systemctl command:
# systemctl reload php7.0-fpm
Note any attempt to exceed these limits will result in a “500 Server Error”. For more information see Linux: 25 PHP Security Best Practices For Sys Admins

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.