While working on a PHP script on a CentOS Linux server that runs from crontab I ran into an issue where PHP was bogging the server down because of memory use. The script has a lot of output that is not necessary to store though when using the exec function within the PHP script it was storing the unneeded output to an away which I believe was causing the memory usage problem. At first I thought I simply needed to modify the memory_limit setting within php.ini however that was not the true issue at hand. Below I describe two items to look at modifying if you run into a similar issue.
Modify PHP Script That Uses The Exec Function And Runs From Cron:
The exec function allows you to store the output from the command that is being executed into an array as well as to store the return status of the executed command as shown in the below example from the PHP manual.
PHP Exec Function Details:
- string exec ( string $command [, array &$output [, int &$return_var ]] )
- exec (/path/somescript.sh, $output, $return);
As you can see above the somescript.sh is the actual command executed within PHP using the exec function. The $output is the array of the output from somescript.sh and $return i the return code once the command has finished executing. So what I believe the issue was when running code this way is that all of the output was being stored in the array and continued to grow in memory. So instead of using exec you can use the system function which provides the same functionality but instead of the output going to an array it is suppressed and you simply rely on the return status in your PHP script to determine what to do once the command is executed thus saving the memory on your server.
PHP System Function Details:
- string system ( string $command [, int &$return_var ] )
- system (/path/somescript.sh, $return);
Notice that the system function is similar to the exec function minus the output to an array. Once I modified this is allowed the PHP script to run for long amount of time without hogging all of the server memory.
Also Check The Scripts Crontab Log Output Configuration:
If you have the PHP script configured in cron to output to a log file you should also consider turning this off once you are done troubleshooting. Once I changed to the system function a ton of blank lines were output to my log file and so all of the writing to disk caused LOAD issues on the Linux server as well.