tags:

views:

111

answers:

5

Is it possible to "call" a PHP script in a loop like this ?

...
while (...)
{
...
header("Location:myscript.php");
...
}
...
A: 

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.

Byron Whitlock
because this script already exist and I don't want to trsnsform it in function
marc bertaud
+3  A: 

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?

Pekka
+1  A: 

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();
    ...
}
...
Yacoby
yes i know but this script is already used and I should modify my code.I will be obliged to create a clone and trnsform it as you suggest
marc bertaud
A: 

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.

BalusC
see the explanation ...
marc bertaud
Someone suggested me this:register_shutdown_function('doRedirect');function doRedirect() { header('Location: url'); exit;}
marc bertaud
A: 

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).

pygorex1
it is the case ...
marc bertaud