Page 1 of 1

Statement execution order

Posted: Mon Sep 26, 2005 2:57 pm
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'.

Posted: Mon Sep 26, 2005 3:00 pm
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

Posted: Mon Sep 26, 2005 3:00 pm
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

Posted: Mon Sep 26, 2005 3:02 pm
by Ree
I thought if it finds header, it stops and redirects. I was wrong :P. Thanks for explaining.