Statement execution order

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

Statement execution order

Post by Ree »

Here's a funny thing. Note the the code below:

Code: Select all

<?php

if (empty($_POST['user']))
{  
  $_SESSION['msg'] = 'Username is empty.';
  header('location: ' . request . '/index.php');
}
if (empty($_POST['pass']))
{
  $_SESSION['msg'] = 'Password is empty.';
  header('location: ' . request . '/index.php');
}

echo 'You should never see this if one of your fields is empty.';

?>
It's a simple test script which accepts two $_POSTs and if any of them is empty, redirects to another script and displays a message. Now what I do not understand is this: even if I leave both fields empty, i get 'Password is empty.' message. But that's incorrect, I should get the first message ('Username is empty.'), since it would trigger the redirect first.

On my another script (the one which I am actually working on atm) it's even more weird, because there, even if both fields are submitted empty, it executes the code below the two if statements, as if they didn't exist.

Btw, if I used else, then it would work just as expected.

Code: Select all

<?php

if (empty($_POST['user']))
{  
  $_SESSION['msg'] = 'Username is empty.';
  header('location: ' . request . '/index.php');
} else
if (empty($_POST['pass']))
{
  $_SESSION['msg'] = 'Password is empty.';
  header('location: ' . request . '/index.php');
} else
{
  echo 'You should never see this if one of your fields is empty.';
}

?>
I really can't find the cause of such 'behaviour'.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

the full script still executes after it hits your header call. it's not like it suddenly stops processing. If you want it to stop processing the page at that point, use exit
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

it will process the code as far as it can, when you use a header then it will go until there would be some output. you have to put in die(); after you want it to actually send the header

edit: sigh, im far too slow today
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

Post by Ree »

I thought if it finds header, it stops and redirects. I was wrong :P. Thanks for explaining.
Post Reply