1

I have a little issue with my code which is causing a problem. The cron service I use automatically timeout each file after 30 seconds. Additionally if you send back too much data it once again times out.

Therefore I need to achieve 2 things.

  1. Send back OK status to the cron service but continue running the php file.
  2. Return little to no data therefore even if data is being output by the file the cron service shouldn't have knowledge of this.

For the longest time now I have used the following code which solved both of these problems

ob_end_clean();
header("Connection: close");
ignore_user_abort(true); // just to be safe
ob_start();
echo('Script Started.');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
sleep(30);

This code worked fine when I needed to run one php file without any interruptions however now my files chain on from each other so when one completes it automatically loads another using this method below

header("Location: anotherfile.php");

I can't just call them all separately because they pass session data between themselves.

Any help would be appreciated.

Thanks.

HP.
  • 63
  • 2
  • 10
  • 1
    Possible duplicate of [continue processing php after sending http response](https://stackoverflow.com/questions/15273570/continue-processing-php-after-sending-http-response) – Tin Can Jul 26 '19 at 22:17

1 Answers1

1

You can't send a redirect to the browser as your code sends an early response. Therefore the browser isn't expecting anymore data.

I would try includeing your files, rather than using redirects. This will mean that they will all be run in the same request.

Please note that you may have to modify the scripts, to skip the response logic after the first script.

<?php

ob_start();

// Send your response.
echo "Background job started";
$size = ob_get_length();
header("Content-Encoding: none");
header("Content-Length: {$size}");
header("Connection: close");
$responseSent = true;

// Flush all output.
ob_end_flush();
ob_flush();
flush();

// Instead of redirecting to the file, simply `include` it
// That way, it will have access to the session/request data
require 'anotherfile.php';
// In the file., skip the response logic if `$responseSent` is set

if (empty($responseSent)) {
    ob_start();
    // response logic
}

// job logic

// when that finishes, move onto the next script
require 'anotherfiletwo.php';
atymic
  • 3,093
  • 1
  • 13
  • 26