PHP header in a loop
Is it possible to "call" a PHP script in a loop like this ?
...
while (...)
{
...开发者_JAVA百科
header("Location:myscript.php");
...
}
...
Nope. header("Location: ...")
is supposed to redirect the browser to a different page, so only one of the calls you make will take effect.
What do you want to do?
You can always include
the script from another to execute it's logic:
include('myscript.php');
In principle, this shouldn't require refactoring any myscript.php code. Be forewarned - myscript.php and the containing script will share the same global namespace, which may introduce bugs. (For instance, if the container outputs HTML and myscript calls session_start()
a warning will be generated).
What you propose should work fine, however not in the way you expect. The header() function simply sends information to the browser in a single batch before the script content (You modify the http headers). So when the script finishes execution the browser will go to the specified page, hence only the last call to header('Location...
will have any effect and that effect will only happen when the php script has finished executing.
A good way to do what I think you want to do would be to encapsulate the functionality of 'myscript.php' into a function.
include 'myscript.php';
while (...)
{
...
myscriptFunction();
...
}
...
You can call header()
in a loop, but with the location header, the browser will only follow one.
location:<url>
tells the browser to go to the url specified. it is known as a 301 redirect. Why you would call it in a loop, I don't know.
No. Rather pass it as a request parameter, assuming you're trying to redirect to self. E.g.
<?php
$i = isset($_GET['i']) ? intval($_GET['i']) : 10; // Or whatever loop count you'd like to have.
if ($i-- > 0) {
header("Location:myscript.php?i=" . $i);
}
?>
I however highly question the sense/value of this :)
Update, you just want to include a PHP script/template in a loop? Then use include()
instead.
while ( ... )
include('myscript.php');
}
If it contains global code, then it will get evaluated and executed that many times.
精彩评论