当我从VS代码提供页面时,PHP Header()重定向正在工作,但是当我从cron作业或CLI启动脚本时,它不是
我有一个简单的PHP脚本,该脚本查询MySQL DB和DELETES(UNLINK)文件,当满足条件(到期时间戳)时。然后它重定向到另一个PHP脚本。我已经设置了一个cron作业以自动运行第一个脚本,这可以正常运行并从上传文件夹中删除所需的文件,但是当我的if-else语句被触发时,它不会重定向。如果我手动将文件路径粘贴到浏览器,则脚本将按照我的期望运行,删除和重定向。 (如果我从CLI运行PHP文件,也不会重定向)。任何帮助都将不胜感激。
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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
标题
函数只是在脚本结束时会发出HTTP响应标头要发送回客户端。显然,这只有在HTTP请求的上下文中才有意义。再次希望通过CLI或CRON运行脚本不是HTTP上下文是不言而喻的。因此,发布任何类型的响应标头,例如
位置
,都不会产生任何效果。请记住,浏览器实际上在网站上看到的重定向的类型 - 服务器仅告诉浏览器(通过位置标头),希望浏览器下一个。在您的CLI/CRON情况下,如果您想运行另一个脚本,一个选项仅为
需要
,例如,这意味着它将执行为当前脚本的延续。
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.This will mean it executes as a continuation of the current script.