hi
i am using xajax framework
i want redirect my url in for loop. every time its go to the home.php at last
my sample code is this
for($i=0;$i<4;$i++) {
if($i == 1) {
header("index.php")
} else {
header("home.php")
}
}
hi
i am using xajax framework
i want redirect my url in for loop. every time its go to the home.php at last
my sample code is this
for($i=0;$i<4;$i++) {
if($i == 1) {
header("index.php")
} else {
header("home.php")
}
}
Well, since the start value of '$i' is 0, the else-block will be called the first time which points to home.php.
Why even have a loop to do this? It makes no sense.
What exactly is the point of that code? You can only have one redirect in your script.
And, it should be written like this:
header('Location: home.php');
exit;
without the exit, the code keeps running.
It's a simple mistake that I fall into a lot myself, but header() can set plenty of different headers; you need to actually specify the Location header (with the page to redirect to):
header("Location: index.php")
I agree with this post: http://stackoverflow.com/questions/1304890/redirect-problem-in-for-loop-in-php/1304896#1304896
But if you still want to do this, you can find some workaround by passing a variable defining that your loop has already been executed + you should end execution while redirecting page.
You can use this code and change in your way:
if(!isset($_GET['ex']) || $_GET['ex'] != '1') //can use ether isset or/and check its value
{
for($i=0;$i<4;$i++)
{
if($i == 1)
{
header("index.php?ex=1");
die(); //or exit();
} else {
header("home.php?ex=1");
die(); //or exit();
}
}
}
The point is that after a redirect, its a whole new page load. PHP starts everything a new, so your loop will be started new. That means on every page $i will start at 0 and loop to 3.
header("Location... does not automatically redirect you, you have send something to the user or stop the page (with exit or die) to send the headers. So your for loop will always redirect to home.php because it's the last header set in the for loop, not because its the first.