'PHP header() redirect is working when I serve the page from VS code, but not when I fire the script from a cron job or a Cli

I have a simple PHP script that queries MySQL DB and deletes(unlinks) file(s) from an uploads folder when a condition (expiry timestamp) is met. Then it redirects to another PHP script. I have set up a cron job to run the first script automatically, this works fine and deletes the files where needed from the uploads folder, but it does not redirect when my if-else statement gets triggered. If I manually paste the file path to the browser, the script runs, deletes and redirects as I would expect. (Also will not redirect if I run the PHP file from the CLI). Any help would be much appreciated.

include_once 'db.php';

date_default_timezone_set("Asia/Bangkok");
$date = date('Y-m-d H:i:s');
$sql = "SELECT name FROM files WHERE expiry <= '$date'";
$result = mysqli_query($conn, $sql);

if (!$result) {
    echo('Could not get data: '.mysqli_error());
}
while ($row = mysqli_fetch_array($result)) {
    $delete = ("assets/uploads/{$row['name']}");
    if (file_exists($delete)) {
        unlink($delete);
    } else {
        header("Location: expire.php", 
            true, 301);
        exit();
    }
}

mysqli_close($conn);


Solution 1:[1]

The header function just issues a HTTP response header to be sent back to a client when the script ends. Clearly, that only makes sense in the context of a HTTP request.

And again hopefully it's self-evident that running the script via CLI or cron is not a HTTP context. Therefore, issuing any kind of response header, such as Location, won't have any effect. Remember that the kind of redirect you commonly see on websites is actually done by the browser - the server merely tells the browser (via the Location header) where it wants the browser to go next.

In your CLI/cron situation, if you want to run another script, one option is simply to require it, e.g.

else {
   require "expire.php";
   exit();
}

This will mean it executes as a continuation of the current script.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ADyson