user15336984
user15336984

Reputation:

Is there a way to redirect in php only if a variable meets a specific condition?

I have something like

Is this possible?

if(this works){
echo "this works";
header( "refresh:5;url=wherever.php" );
}else{
echo "it didnt work";
header( "refresh:5;url=somewhereelse.php" );
}

Upvotes: 2

Views: 78

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94642

No, but only because you do an echo before you attempt to do the header() you cannot send headers to the browser AFTER you have sent any of the page. echo will start the process of sending data to the page as will anything, even a space before your <?php would do that

But assuming you have no other output sent to the browser before you run this code you could do

if($sometest){
    header( "refresh:5;url=wherever.php" );
    echo "this works";
}else{
    header( "refresh:5;url=somewhereelse.php" );
    echo "it didnt work";
}

However in reality the echo would never get to the browser (current Page) as you are redirecting to another page, so you can just do

if($sometest){
    header( "refresh:5;url=wherever.php" );
}else{
    header( "refresh:5;url=somewhereelse.php" );
}

If you really have to see the message you woudl have to add it to the querystring of the redirected pages, or put it into the SESSION and the then the redirected pages would have to look for the message and send it as part of their page content.

Upvotes: 2

Related Questions