RKh
RKh

Reputation: 14159

[PHP]: Why page is not redirecting?

In the following code, the "header:" line is giving problem.

  $q = mysql_query($a) or die(mysql_error());
  $row = mysql_fetch_array($q);

      $ValidationResponse = "false";

      if ($_COOKIE['user_name'] != "")
        {
  while ($row) {
      if ($_COOKIE['user_name'] = $row['username'])
      {
              $ValidationResponse = "true";
              break;
          }
      }
        if ($ValidationResponse == "true")
        {
            ob_start();
            header("location:personal_view.php");
            ob_clean();
        }
        else
            echo "<script>alert('Invalid Login. Try Again.');</script>";
        }
          $_COOKIE['user_name'] = "";

Upvotes: 0

Views: 281

Answers (3)

rubayeet
rubayeet

Reputation: 9400

This might sound stupid, but are you sure you are not outputting anything before the header() function call? Apache won't redirect even if it finds a newline character before the starting tag <?php in a script.

Upvotes: 0

cletus
cletus

Reputation: 625387

Three useful functions I tend to have:

function redirect($url) {
  while (ob_end_clean()) ; // do nothing
  header("Location: " + $url);
  exit;
}

function reload() {
  redirect($_SERVER['REQUEST_URI']);
}

function reloadQS() {
  redirect($_SERVER['REQUEST_URI'] + '?' + $_SERVER['QUERY_STRING']);
}

The above correctly handles what might be nested output buffers already but will fail if content has already been sent to the user, which you can't do anything about. I'd suggest using the above otherwise you'll litter your code with loops to clean buffers and there's no point in that.

You're using output buffering incorrectly, which is why it's failing. Change:

ob_start();
header("location:personal_view.php");
ob_clean();

to:

ob_end_clean();
header("Location: personal_view.php");
exit;

Upvotes: 2

The Disintegrator
The Disintegrator

Reputation: 4187

You should put the ob_start at the very beginning of the script Also, i'm not sure about this, but i always seen the location header written in this way

header("Location: location.php");

Location with capital L an a space after the colon ": "

Upvotes: 0

Related Questions