1

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

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

5 Answers 5

3

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?

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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();
    ...
}
...

1 Comment

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
0

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.

1 Comment

because this script already exist and I don't want to trsnsform it in function
0

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.

1 Comment

Someone suggested me this: register_shutdown_function('doRedirect'); function doRedirect() { header('Location: url'); exit; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.