1

For some reason my code is skipping couple of parts even though they seem correct. The code just executes the last header function. The problem seems to be of these headers. How to make this work?

<?php
$values = [
'orderperson',
'address',
'postnumber',
'city',
'phone',
'email'
];

$shipvalues = [
'recipient',
'address1',
'postnumber1',
'city1',
'phone1',
'email1'
];

foreach($values as $value) {
 if(empty($_POST[$value])) {
  header("Location: http://example.com?errors=true");
 }
}

if (array_key_exists("checkbox", $_POST) && !empty($_POST['checkbox'])) {
  foreach ($shipvalues as $shipvalue) {
    if(empty($_POST[$shipvalue])) {
     header("Location: http://example.com?errors=true");
    }
   }
 }

header("Location: http://example.com");
exit;
tuomvii
  • 55
  • 6
  • After each header you might have to put a die; sometimes when my wifi connection is slow it skips past the header. – Riz-waan Jan 21 '19 at 19:21
  • Is there a difference if I use die or exit? – tuomvii Jan 21 '19 at 19:23
  • Nope no difference, check this out https://stackoverflow.com/a/1795031/8171863 – Riz-waan Jan 21 '19 at 19:24
  • Possible duplicate of [Header location not working properly](https://stackoverflow.com/questions/3519807/header-location-not-working-properly) – rsm Jan 21 '19 at 19:29

1 Answers1

2

The following code should work:

<?php
$values = [
'orderperson',
'address',
'postnumber',
'city',
'phone',
'email'
];

$shipvalues = [
'recipient',
'address1',
'postnumber1',
'city1',
'phone1',
'email1'
];

foreach($values as $value) {
 if(empty($_POST[$value])) {
  header("Location: http://example.com?errors=true");
  exit;
 }
}

if (array_key_exists("checkbox", $_POST) && !empty($_POST['checkbox'])) {
  foreach ($shipvalues as $shipvalue) {
    if(empty($_POST[$shipvalue])) {
     header("Location: http://example.com?errors=true");
     exit;
    }
   }
 }

header("Location: http://example.com");
exit;

The reason this would be better and efficient is that you stop all operations once an error has been detected, allowing for the lack of wasted processing.

This is also recommend as if the server is faster than network connection then your server will move on with code overwriting the header function. This has happened to me once when I was testing it on a different network.

If you want to know all the errors then I suggest you create an error array and fill it with the errors then check wether it is empty and redirect accordingly.

Riz-waan
  • 603
  • 3
  • 13
  • For future notice, should I always use die; / exit; after header function? – tuomvii Jan 21 '19 at 19:31
  • @tuomvii Yes you should always use either one after a header function. I also recommend you use the same one throughout your code for consistency. – Riz-waan Jan 21 '19 at 19:32