spartak
spartak

Reputation: 153

header vs content redirect

As we know it, the header() function in PHP causes error ouputs unless sent before an HTML content, so instead of using output buffering or worse yet, suppressing the famous "headers already sent " error, I was thinking of using the HTML content redirect as an alternative. ex:

if($userRegister){ ?>
   <meta http-equiv="refresh" content="0; URL=success.php" /> 
<?php }

As I have not seen this approach, I would like to know there is something I am missing. Because it seems quite a good approach for page redirection

Upvotes: 2

Views: 1791

Answers (4)

roninblade
roninblade

Reputation: 1892

i would personally use headers_sent instead of checking a specific variable since that's why the function was created in the first place

if (headers_sent()) {
  echo '<meta http-equiv="refresh" content="0; URL=success.php" />'
}

i also suggest creating redirect method so you don't have to test the headers each time in different parts of your code

function redirect($target) {
  if (headers_sent()) {
    echo "<meta http-equiv=\"refresh\" content=\"0; URL={$target}\" />";
  } else {
    header("Location: {$target}");
  }
  exit;
}

Upvotes: 1

user3771071
user3771071

Reputation: 16

You have used meta refresh as an alternative of header location. It's right but in my opinion you should use header redirect and if you want to remove header already sent error than you should use ob_start() and ob_flush() and turn on the output buffering your php.ini if it's off.

Upvotes: 0

Brad Zacher
Brad Zacher

Reputation: 3243

see: Is it good practise to use meta refresh tags for redirects instead of header() function in php?

both methods have their ups and downs.

in my opinion it is better to use header() as it sends a smaller payload to the client and it won't cause side effects from the browser loading the DOM of another page.

Upvotes: 1

DavidT
DavidT

Reputation: 461

This isn't required, but I'd suggest doing something like this:

if($userRegister){ ?>
<script type="text/javascript">location.href="success.php";</script>
<noscript><meta http-equiv="refresh" content="0; URL=success.php" /></noscript> 
<?php }

Upvotes: 2

Related Questions