In this article we will discuss how can you set up memory limit value for your PHP scripts using php.ini file. We will learn multiple ways to set memory limit. Let's start
What is PHP script memory limit?
This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts from eating up all available memory on a server.
What is php.ini file?
The php.ini file is a special file for PHP. It is where you declare changes to your PHP settings. The server is already configured with standard settings for PHP, which your site will use by default. Unless you need to change one or more settings, there is no need to create or modify a php.ini file.
How to edit php.ini file?
In order to set a desired value for memory limit of your PHP scripts, you will need to edit this file. This file is present in your PHP installation folder. There are two cases that arise here.
1- If you are using locahost
This solution is for those who are running a server on localhost. If your operating system is Windows, you can locate your php.ini file from this location. C:\xampp\php\php.ini. It is assumed that your xampp installation is located in C Drive on your Windows PC. If not, then locate your xampp installation on your PC and navigate to /php/php.ini. If you are using Linux, then most distributions put lampp under /opt/lampp, so the file can be found under /opt/lampp/etc/php.ini.
Open your php.ini file and then search for the term memory_limit. Change its current value to whatever you want to set. Remember its value represents the maximum number of time in seconds you want to allow your PHP script to run. Below I am showing a portion of my php.ini file that contains this directive.
; Maximum amount of memory a script may consume
memory_limit = 128M
Note: After making changes to php.ini file, you have to restart the apache server. By this setting, the configuration is made global to all PHP scripts. Changes done to this file in an incorrect way can create problems to the web-server or live projects. To restart your apache server (if its already running first close it then) click on start button next to it. Now your changes in php.ini file should get effective.
2- If you are using a remote server
If its a remote server, then login to your Cpanel. The interface of Cpanel can be different for different hosting companies but you the basic idea is always the same. Look for PHP settings inside Cpanel dashboard, then look for the term memory_limit. Set up your desired value and save it.
3- Using PHP built-in function memory_limit()
If somehow you are not able to use any of the above 2 methods to increase the execution time, you can do so using your PHP code. Place this code at the start of your PHP script so it applies before your script executes your main code.
ini_set('memory_limit', '300MB'); //feel free to change this value as per your requirements