Hi there,

I am wondering does anyone have any idea how to execute PHP scripts (a maintenance script in my case) in the background. The reason for this is because I don't want visitors to be slowed down by the maintenance execution, so having it run as a separate process would help a lot.

I have thought about running cron jobs but I want to enforce a maintenance if cron job stops working for some reason.

Any help or ideas would be greatly appreciated.

tim

Dani AI

Generated

Short summary and practical direction: the goal is to trigger a maintenance task from a web request but not make the visitor wait or let the web request become the bottleneck. Several good ideas are already in the thread — ’s ad-hoc run-on-admin-login, ’s cron suggestion, ’s Windows/PsExec pointer and ’s exec/http tricks — but a production-safe solution usually mixes a lightweight web trigger with a separate worker process that actually does the heavy work.

Recommended pattern (simple to robust)

  • Lightweight trigger: a web handler inserts a job record (or pushes a message) into a queue table or job queue and immediately returns a short response. The insertion is cheap and fast.
  • Worker: a separate PHP CLI script (or worker using Redis/RabbitMQ/beanstalkd) picks queued jobs and processes them. Run the worker under a supervisor (systemd, supervisor) or cron that runs every minute. This keeps the web process tiny, makes tasks reliable, and avoids client timeouts.
  • Fallback/watchdog: have the worker write a heartbeat/last-run timestamp. A simple watchdog can restart the worker or re-queue jobs if the heartbeat is stale — this addresses the “cron stops working” concern.

Quick server-side tricks (when installing a worker is not possible)

  • Close the HTTP response immediately and continue processing on the same process when the SAPI supports it (fastcgi_finish_request), and always release session locks first. Example pattern:
<?php
session_start();
session_write_close();
ignore_user_abort(true);
if (function_exists('fastcgi_finish_request')) {
    echo "OK";
    fastcgi_finish_request();
}
// long work here (set_time_limit(0) in CLI worker)
do_maintenance();

Caveats and troubleshooting

  • Session locking: call session_write_close() before any long work to avoid blocking other requests.
  • Disabled functions / hosting limits: exec/proc_open/pcntl may be disabled on shared hosts; HTTP tricks may hit webserver/FPM timeouts.
  • Concurrency: use flock or a DB job-status update to avoid duplicate workers.
  • Security and logging: protect any web-triggered endpoint with auth/secret tokens, log progress to files/syslog, and rotate logs.
    For reliability in production, prefer a queued-worker architecture supervised by the OS; it scales and avoids fragile hacks that depend on specific PHP functions or server timeouts.

Recommended Answers

All 9 Replies

PHP script always executed at the background, if not mistaken.

I run my maintenance routine everytime I log in to my admin area. It will not affect my clients' site and yet keep my database clean. I log in at least once a week and did not notice any delay or slow down. I think you can do the same.

If you are working in a webserver you have full access to, you can also setup a cronjob!

But be aware, that your code should log errors and message to logfiles instead of the console.

Thanks guys ;)

I was just hoping of an idea to run a php script initiated by a visitor where a user wouldnt have to wait for the whole maintenance execution. I guess kind of like branching a single process into two. Thats something I havent done before; Im not sure if its possible.

How about you have a cron job but you also have it so that it can be run from the browser or from the shell. Do you need it running all the time?

Thanks guys ;)

I was just hoping of an idea to run a php script initiated by a visitor where a user wouldnt have to wait for the whole maintenance execution. I guess kind of like branching a single process into two. Thats something I havent done before; Im not sure if its possible.

Have a look at the PsExec tools (google it). With it you can run an external program, and choose to wait for it. This could do what you need.

Thanks guys ;)

I was just hoping of an idea to run a php script initiated by a visitor where a user wouldnt have to wait for the whole maintenance execution. I guess kind of like branching a single process into two. Thats something I havent done before; Im not sure if its possible.

Hi,

What you could do is use the exec() function in PHP that always to to execute shell commands. (Also see: popen, and proc_open() )

You can use the & option to run the command in the background.

Example:

<?php
exec( 'wget  > /dev/null &' );
?>

The > /dev/null sends your php output to nowhere.
The & makes the wget run in the background.

You can use other commands rather than wget, but thats one Im sure of the syntax for.

If you cant use exec() then you could try using the HTTP protocol to your advantage to fork your php script for you.

I havent tested but I believe if you could do something like:

header( 'Location : ' );
echo str_pad(' ', 256); // make IE start rendering
flush();

// Do your other stuff here, in the background 
// The browser is now fetching 
// Make sure you dont output anything

run_my_maintanence();

I believe this will work.
For IE to actually start following the HTTP headers, it has to receive at least 256 bytes of content.. (now why?)

See if either of those work for you.

PHP does always run in the background it is server side scripting. something like javascript which is client side would run in the foreground.

impressive wget option. I wasn't aware of that :)

Sorry for not clarifying: run in the background I meant run as a separate process which will not be a bottleneck for the main process.

Thanks very much
tim

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.