Page 1 of 1

session_start() and header('location')

Posted: Thu Feb 15, 2007 8:02 pm
by shwanky
Ok, so I'm stupid that I didn't realize this earlier. Like 2 years earlier, we won't talk about that. So for sometime now, I've been trying to figure out how to redirect using the header function once session_start has been called. Up until now I've been using a function similar to this:

Code: Select all

<?php

function redirect_to($url)
{
     if(!headers_sent())
     {
          header('location:' $url);
     }
     else
     {
         echo '<meta http-equiv="refresh" content="0;url='.$url.'">';
     }
     exit();
}
?>
However, today I found a simpler way to get it done. I actually RTFM, for once.

Code: Select all

<?php

@session_start();
$_SESSION['var'] = 'Test';
@session_write_close();
header('location: http://www.google.com');

?>
Hope this help's someone. For everyone else, please don't laugh to hard :(.

Posted: Thu Feb 15, 2007 9:41 pm
by superdezign
Never knew that. Actually, I wasn't aware that you couldn't send headers after session_start(), but I was aware that you can send headers before it.

Usually, my redirecting is done before sessions are called in an if statement, so I've never run into the problem. Thanks for posting the solution though. I don't see a lot of people giving solutions to problems that haven't bee posted as a question.

Posted: Thu Feb 15, 2007 10:45 pm
by feyd
It's been posted as a question (problem) on several occasions.

Posted: Fri Feb 16, 2007 2:14 am
by arukomp
This is how I redirect to other pages even when headers are sent. This always works:

Code: Select all

echo "<script>document.location.href='http://www.google.com'</script>";
This always works for me and I think it's quite simple :)

Posted: Fri Feb 16, 2007 2:39 am
by shwanky
arukomp wrote:This is how I redirect to other pages even when headers are sent. This always works:

Code: Select all

echo "<script>document.location.href='http://www.google.com'</script>";
This always works for me and I think it's quite simple :)
No it doesn't. If someone where to disable javascript in there browser, something I do quite often, the redirect would fail.

Posted: Fri Feb 16, 2007 2:43 am
by RobertGonzalez
You could use HTML meta redirection. And you should stop using error suppression.

Posted: Fri Feb 16, 2007 3:18 am
by shwanky
Everah wrote:You could use HTML meta redirection. And you should stop using error suppression.
I don't use error suppresion in my applications. Just for the example. Error logs for the win ^.^

Posted: Fri Feb 16, 2007 8:11 am
by feyd
shwanky wrote:I don't use error suppresion in my applications. Just for the example. Error logs for the win ^.^
The code posted has error suppression however. It should still use headers_sent() as well.