Andy
Andy

Reputation: 3021

PHP Post & Redirect

I have the following code which checks the post for a "no" and if it exists prints and error or if not it redirects. It currently redirects everytime regardless of the fact the post array has 'NO' as a value.

if($_POST["minRequirementsForm"] == '1') {
     foreach($_POST as $key => $value) { 
        if ($value == 'no') {  
            $error = 1; 
        } else { 
            header('Location: mysite.com/app-stage1.php');
        }
     }
//print_r($_POST);  
}

Upvotes: 0

Views: 594

Answers (3)

Shoe
Shoe

Reputation: 76240

Don't use it as you did. Just write:

if (in_array('no', $_POST)) { $error = true; }
if (!$error) { header('Location: mysite.com/app-stage1.php'); }

It's better to use an already existing functions in php than reinvent the wheel. Or use the following, which is more appropriate:

if (!array_search('no', $_POST)) { header('Location: mysite.com/app-stage1.php'); }

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545558

Just use the header call after the loop, and check for $error:

$error = false;

if($_POST["minRequirementsForm"] == '1') {
    foreach($_POST as $key => $value) { 
        if ($value == 'no') {  
            $error = true;
        }
    }
}

if (! $error) {
    header('Location: mysite.com/app-stage1.php');
}

Notice that this uses the type boolean instead of an integer for the variable $error, which is more appropriate.

Upvotes: 5

Stewie
Stewie

Reputation: 3121

It redirects because of the subsequent values of non "no" strings. It echos the error, but due to next value, it redirects. Try exiting in the if(no) condition and you will see the error.

Upvotes: 0

Related Questions