Looping a PHP Script - php

I've got a PHP script that checks a directory and deletes any files not modified within 15 seconds (It's for a game).
My problem is how to get this script to run all the time. I set up a cron job to run every 10 minutes and then in the PHP script I have an infinite loop with a sleep(10). My thought was that it would run the code every 10 seconds, and in the case the script stopped, the cron job would restart it eventually.
However, after the script is started, it runs for about 3 loops (30 secs) and then stops. I've heard PHP only gets so much memory per file load.
How can I make this PHP script loop indefinitely? Maybe there is some way to call itself

You could run a parent php process that forks a client at an interval. If you're curious about exploring it as an option here is a good starting point: http://ca2.php.net/pcntl Nice thing about doing it this way is that the parent process can kill client pids that do not end within a reasonable amount of time.
If you're looking for something quick and dirty you could write a bash script to invoke the php quite easily (if you're on linux):
#!/bin/bash
while [ "true" ]; do
/path/to/script.php
sleep 15
done
EDIT
You don't really even need the script, bash will do it all on one line:
while [ "true" ]; do /path/to/script.php; sleep 15; done

Make sure your PHP executable is compiled for use as a command-line interpreter, not a CGI executable. PHP normally kills scripts which run for longer than max_execution_time (default is 30 seconds). CLI executables, however, do not impose this limitation.
More info about CLI vs. CGI SAPIs.
You can check your executable's SAPI by using the --version argument:
$ php --version
PHP 4.3.0 (cli), Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

You might want to check your max_execution_time parameter in the php.ini file. I believe the default is 30 seconds. The way you have it setup with cron, you will probably have multiple instances of the script running after 10 minutes unless you add some logic in the script to check that an instance of itself is not already running

PHP as a language is not very good at running indefinitely.
Since you have a cron-job every ten minutes, why not execute your task 60 times and then exit?
Also, PHP has different config files for CLI and for apache modes on most linux servers.
So it might be wise to check your etc/php/cli/php.ini and check maximum execution time and memory limits.

every so often (before you run out of memory) break out of the loop and re-execute itself
exec("/usr/bin/php " . FILE);

There is a PEAR module for writing long-running PHP scripts. I've not used it myself though.

Related

How can I run a daemon on xampp using PHP?

I have an XML database that I want to manage independently from users on my website. Looking into the matter it appears that I should write a daemon script to manage my database. That is all fine and dandy but, I feel like I'm opening a can of worms. I wanted to write my daemon script in PHP, so I looked into PCNTL. But I quickly learned that PCNTL is not suited for web servers. So now I am stumped. How can I get a daemon to run on my server? Do I need to learn another language? I only want to write my own scripts. But I feel lost. I would prefer to write my daemon in PHP as I am familiar with the language.
I have been researching everything from PCNTL, CLI, SO questions, numerous articles on daemon processes... etc
I am running PHP 5.6.32 (cli), windows 7, on Apache. XAMPP 5.6.32. Unix system.
EDIT: I also have windows setup to run PHP from command prompt.
There's nothing wrong in running a PHP daemon, however it's not the fastest thing, especially before the 7.0 version. You can proceed in two ways:
Using Cron Jobs, if you're under Unix systems crontab will be fine, in this way you can specify the interval within the system automatically executes the specified script and then exit.
The true daemon, firstly you need to change the max_execution_time in PHP.ini to 0 (infinite), then in your daemon call for first function set_time_limit(0);, remember to run it only once. However if there is some failure like a thrown error uncatched the script will exit and you need to open it again manually, and don't try...catch in a while loop because it will probably go into an endless loop. Execute the script with php -f daemon.php.

PHP hangs on date calculations

Lately any date operations or calculations in my script hangs until it is killed for taking too long (Maximum execution time of 30 seconds exceeded error). It happens both running the script from Apache or on the command line. All of the date and date/time operations used to work.
The code that hangs can be as simple as new DateTime() or date('Y'), although time() does work.
I'm running PHP 5.6 on a Raspberry Pi 3 with Raspbian Jessie with Apache 2.4.10.
The only date-related change to the system that I can think of is that I added an RTC module and followed the steps in the Adafruit tutorial to configure it. I don't know how that would have affected PHP though. Python's time.localtime() and just a plain ol' date or hwclock on the command line still work as expected.
Edit: I noticed that if I leave the command-line version running and watch it with top, PHP uses 100% of the CPU and the RAM usage increases steadily.
Update: I rolled back the configuration to not use the RTC module anymore, disabled I2C, and reinstalled fake-hwclock. The problem persists. Running php -r 'echo date("Y");' takes all the CPU and slowly takes all the RAM until manually killed. The problem doesn't appear to be related to the hardware RTC module.
I figured it out! I ran php -r 'echo date("Y");' through strace and noticed that it was recursively loading time zones. For example:
openat(AT_FDCWD, "/usr/share/zoneinfo/localtime", ...
eventually followed by
openat(AT_FDCWD, "/usr/share/zoneinfo/localtime/localtime", ...
and then
openat(AT_FDCWD, "/usr/share/zoneinfo/localtime/localtime/localtime", ...
You see the pattern. It turns out the problem was I had a symlink in my /etc/localtime folder called localtime that pointed to... you guessed it: /etc/localtime, so it kept loading the time zones over and over again, which explains the CPU usage and continually increasing RAM usage.

Bash and PHP - Call functions/commands after a certain amount of time

I am very new to PHP and Bash programming and I have some 'basic' questions to ask.
I have created a server using a Raspberry Pi with a PHP scrip which accepts some variables and executes some bash scripts.
That works fine. However, I wanted to add a timer, letting the user to put a certain amount of time in minutes or seconds, or a specific time.
I thought of using the 'cron job', which I'm not familiar with.
What would be your approach? Implementing it in PHP or in Bash and with which function (cron job, some sleep in bash...).
Thank you very much!!
It depends on the frequency with which the jobs need to be run, how much jitter (e.g. must the job run at 02:00:00 or is 02:00:10 OK). Using cron should have less of a memory footprint than a PHP script - and you don't need to worry about memory leaks and the complications o running the PHP as a daemon. OTOH using a PHP script allows for much finer control over when scripts run.
I am very new to PHP and Bash programming
If this is not something you're familiar with and you want to impement the triggering of other processes, then do have a look at the sleep() function in PHP and the corresponding sleep command available from bash.
Install PHP Cli... and call it from cron:
apt-get install php5-cli
and maps at cron the call
crontab -e
and then
0 * * * * /usr/bin/php /var/www/myPage.php
for example, to run every hour.

How to run php script on server through command line

I have created a php script to import rss feed into the database. The feed which is huge (from year 2004 to 2010, approx 2 million records) has to be inserted into the database. I have been running the script in browser but the pace it is inserting (approx. 1 per second) i doubt it takes another 20-25 days to input this data even if i run it 24 hrs a day. I have tried it running on different browser windows at the same time and have finished only 70000 records in last two days. I am not sure how the server would react if i run 10-12 instances of it simultaneously.
A programmer at my client's end says that i could run it directly on the server through command line. Could anyone tell me how much difference it would make if i run it through command line? Also what is the command line syntax to run it? I am on apache, php/mysql. I tried out over the web for a similar answer but they seem quite confusing to me as i am not a system administrator or that good in linux although i have done tasks like svn repositories and installing some apache modules on server in the past so i hope i could manage this if someone tell me how to do it.
Difference in speed: Minimal. All you save on is blocking on NET I/O and connection (and the apache overhead which is negligible).
How to do it:
bash> php -f /path/to/my/php/script.php
You may only have the php5-mod package installed which is php for apache, you may have to install the actual command line interpreter, however a lot of distros install both. Personally I think you have an efficiency problem in the algorithm. Something taking days and days seems like it could be sped up by caching & worst-case performance analysis (Big-O notation).
Also, php vanilla isn't very fast, there's lots of ways to make it really fast, but if you're doing heavy computation, you should consider c/c++, C#/Mono (Maybe), possibly python (can be pre-compiled, may not actually be much faster).
But the exploration of these other outlets is highly recommended.
Only providing the filename to execute is sufficient:
php -f <YourScriptHere.php>
See the documentation for more command line options.
To run a php script in the command line just execute:
php yourscript.php
If you want to keep this process running in background do:
php yourscript.php &
You can then run several processes at the same time. To identify the instances of the script that are currently running execute:
ps aux | grep yourscript.php
However, if you think it takes too long, try to find out whether there's any bottleneck in your code and optimize it.
in linux:
php -f file.php
type
php --help
for other options
You may also need the -n option (no php.ini file) or options to specify where php-cli.ini or php.ini file can be found.

Debug the PHP interpreter with GDB

I would like to use GDB to step though the C++ code that makes up the php.so Apache extension. I want to see what PHP is doing while it's running a PHP application. Preferably I would use an IDE like Netbeans or Eclipse on a LAMP system.
You want to get your hands on a debug build of mod_php (with symbols) or build your own (configure --enable-debug)
You should configure your Apache to always keep exactly one worker process instance up (which will be the instance you debug), that is, set MinSpareServers, MaxSpareServers and StartServers all to 1. Also make sure any timeout parameters are generously set
Use gdb or any graphical interface to gdb (such as ddd or Eclipse CDT) to attach to the one and only Apache worker process. Stick a breakpoint in one of the PHP sources etc. and continue.
Point your browser to your webserver and access a PHP page. Your breakpoint will trigger. If you want to wake the debugger at a particular point in your PHP script execution, generate a SIGTRAP from PHP and gdb will normally oblige you.
Have fun!
Maybe you could do that on windows.
However, your best bet is to do this on a Unix box. You will have to compile everything with debugging enabled. GDB will need access to those directories for source.
Then you will have to run apache and then run the process.
In order to give yourself time to attache while you are hitting the PHP/Apache with a browser, add a sleep call in the PHP script. If you ps, you will see the process in the sleep state. Or you could just have it write its process id to a file in tmp before it does the sleep.

Categories