0

In my case, I want to regularly check my database for expired data, and delete it if it has, so I've added this check to the start of all my PHP web responses. However there's simply no need to do this before the user gets their data, because it's not directly related to them, and I don't want to slow down my website.

I accept that in this case I should probably just schedule a cron task that would run a PHP script, but that doesn’t seem to be a very portable solution. If I migrate servers I would have to manually add this cron task, and it gets even more complicated if I changed platform.

So my two questions are:

  • Is it possible to return some data (either an HTML page, or JSON data etc.), and then execute some PHP code in order to ensure the fastest possible response time?
  • If not, is there some portable way to schedule a PHP script?
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Migwell
  • 18,631
  • 21
  • 91
  • 160
  • 1
    You *can* do this with AJAX and setInterval() but you really shouldn't. Imagine if 100 requests hit your site in the same second. This could cause users to unnecessarily wait while the exact same task is needlessly executed many times. I am also not sure why you claim that switching between Linux and Windows would complicate things. – MonkeyZeus Jun 26 '14 at 16:04
  • 1
    http://stackoverflow.com/questions/8977942/php-close-output-stream that said , you should really manage that in another way. like having some kind of background proccess. or crafting an install script to make the necesary changes on cron – Jarry Jun 26 '14 at 16:06
  • 2
    Assuming you're using MySQL as your database, and your scheduled PHP script would only touch database stuff anyway, you could maybe do this with a [Mysql Event](http://dev.mysql.com/doc/refman/5.1/en/create-event.html)? You would face a similar issue if you migrated servers, but you easily include the event creation. – SubjectCurio Jun 26 '14 at 16:07

1 Answers1

0

You can use shell_exec (or similar functions) to execute a different PHP file (or the script itself) in the background.

Here's an example:

function exec_in_background($cmd) {
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("@start /b \"\" ". $cmd, "r"));
    } 
    else { 
        exec($cmd . " > /dev/null &");   
    }
}

if (isset($argv[1]) && $argv[1] == '--cron') {
    // Your database logic goes here
}

exec_in_background("php \"" . __FILE__ . "\" --cron");

You can just add this to the top of your script and it should do the trick.

Please note that what you are trying to achieve might not be advisable as if there will be many requests you will perform these actions many times.

Razvan
  • 2,436
  • 18
  • 23