Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a php script in the background without curl

Tags:

php

curl

Im having a little trouble with running a php script in the background.

I have my admin area which has HTTP authentication to access and a mail out script which I want to run in the background. This script will take a long time to execute so I wish it to execute in the background.

My idea is when I access the "send" page, it executes the send script in the background and redirects the user off elsewhere.

However currently attempting to use cURL I cannot cURL into the send script as it returns Authorization required.

Any advice appreciated, thanks.

like image 647
pondpad Avatar asked Sep 12 '26 12:09

pondpad


2 Answers

  1. Create some queue of jobs (database / files / writing directly to some socket).
  2. Create either a deamon (socket) or cron job which consumes those jobs.
  3. Let the worker report when a task is done in some store if needed (database / file / etc.), if you want to provide a 'success' (or failure) message later on.
like image 165
Wrikken Avatar answered Sep 14 '26 03:09

Wrikken


You might try pcntl_fork() if you're running it on Linux. Note that this approach requires some magic on the PHP installation part (pcntl is disabled by default for cgi) and even more magic to make your script survive apache process cleanup. See this comment on PHP to get you started.

So forking off a process would look like this:

if ($pid = pcntl_fork())
    die();     // Parent

function shutdown() {
    posix_kill(posix_getpid(), SIGHUP);
}

ob_end_clean(); // Discard the output buffer and close

fclose(STDIN);  // Close all of the standard
fclose(STDOUT); // file descriptors as we
fclose(STDERR); // are running as a daemon.

register_shutdown_function('shutdown');

if (posix_setsid() < 0)
    die();      // <- This is an error

if ($pid = pcntl_fork())
    die();     // Parent

// Do your stuff here
like image 38
svens Avatar answered Sep 14 '26 01:09

svens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!