Jump to content

Question about header redirection and if/else statements..???


angelleye

Recommended Posts

I've got some scripts setup that have if statements inside them but I like to avoid using else unless I really need it.  For example, something like...

 

if(count($Errors) > 0)
{
     $_SESSION['Errors'] = $Errors;
     header("Location: error.php");
}

// if no error go ahead and move on.  No need for else because if there is error it redirects away from here anyway.

 

That idea seems to work fine for me as long as I don't end the whole page with a redirect.  An example of when this happens is when I've got a script that's adding all of the order info to a DB and at the end redirects to a successful/receipt page.  The very last thing on this script would be a redirection. 

 

The problem is that if I have something like the following...

 

if(count($Errors) > 0)
{
     $_SESSION['Errors'] = $Errors;
     header("Location: error.php");
}

// no errors so call was successful, redirect to paypal
header("Location: payment-complete.php");

 

and there are indeed errors in $Errors it doesn't redirect to the error.php page.  I end up at my payment-complete.php page with errors because of course it doesn't get all of the data it expects since the error occurred and it should ahve never reached that page to begin with.

 

What's interesting is that if I remove the redirect at the very bottom where I assume everything works and just do something like echo a line..

 

if(count($Errors) > 0)
{
     $_SESSION['Errors'] = $Errors;
     header("Location: error.php");
}

// no errors so call was successful, redirect to paypal
echo 'it worked';

 

Then it does indeed redirect to my error.php as it should when errors occur. 

 

So it seems like the entire PHP script is getting parsed and if there are no PHP failures then the final header() just loads regardless.  But if I don't have a header() outside of my if statements then they will indeed work inside those if statements.

 

I hope I explained that well enough.  I'm confused about why it's happening.  Any information on this would be greatly appreciated.  Thanks!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.