問題描述
Tập lệnh PHP có thể tiếp tục sau khi chuyển hướng không? (Is it possible for PHP script to continue after redirect?)
I am working on an existing website, looking for security issues. Is it safe to say that a PHP script aborts after the browser is redirected away or can a crafty user somehow force the script to continue. Assume "is_logged_in" returns 1 or 0 if the user is currently logged in. Assume there are no vulnerabilities in this function. The code is as follows:
<?
$fp = fopen("./debug.txt", "a");
fwrite("BEFORE LOGIN CHECK\n");
if(!is_logged_in()) {
fwrite("Not authed \n");
header("Location: $url", TRUE, 302);
}
fwrite("Passed auth check \n");
/* Code to do some logged in functionality here */
?>
Using a normal browser with a logged in user I get
BEFORE LOGIN CHECK
Passed auth check
with a not logged in user I get
BEFORE LOGIN CHECK
Not authed
Is it possible to hold the script open (and ignore the redirect), using raw requests so that I get
BEFORE LOGIN CHECK
Not authed
Passed auth check
Essentially go into the if block, get the redirect header, ignore it, and have the script continue executing.
If not I would correct the issue by doing:
if(!is_logged_in()) {
fwrite("Not authed \n");
header("Location: $url", TRUE, 302);
die();
}
But I'm not sure if this is even an issue.
參考解法
方法 1:
Correct, you need to use exit();
or die();
after that header to stop PHP from executing.
By using header()
you are simply setting a single HTTP header, which to PHP means nothing. You can set header('X‑CHEESE', 'cheddar');
and it's going to execute that fine, then carry on with the processing.
The die you used will tell PHP to stop executing, then the browser will take over, so when it spots the Location: it will go to the URL provided.
方法 2:
If you don't exit;
after the header then the script should continue to run.
I have used this before when sending HTTP 200 to the client, and content‑length: 0. So the client doesn't do anything, and PHP continues executing.
方法 3:
The header method doesnt end the script execution, so the user would get a redirect header, but the rest of the script would still execute (and this is dangerous).
Either die() or exit your code after the redirect.
EDIT:
After a test with the following code:
$fp = fopen("debug.txt", "a");
fwrite($fp,"BEFORE LOGIN CHECK\n");
if(true) {
fwrite($fp,"Not authed \n");
header("Location: index.php", TRUE, 302);
}
fwrite($fp,"Passed auth check \n");
fclose($fp);
Changing the value inside the if to false appends this to the debug.txt file:
BEFORE LOGIN CHECK
Passed auth check
Changing it to true appens this to debug.txt:
BEFORE LOGIN CHECK
Not authed
Passed auth check
(by user2072710、Phil Sturgeon、Mr_Tom、cernunnos)