Reputation: 1129
This seems like it should be simple enough but I'm having a little trouble.
I have an index page which is both the login page and the main content page, depending on whether or not a session variable is set.
I've tried using JavaScript which is echoed from PHP to handle redirects but it looked sloppy and takes a little bit of time, so I switched to using header("location: abc.php"). The problem with using that for the index page is that it doesn't work after output is sent. I've also tried using a meta tag to refresh the page but that doesn't work in all browsers.
What's the best way to handle this situation?
Thanks in advance.
Upvotes: 0
Views: 673
Reputation: 781130
Does this do what you want?
<?php
session_start();
if ($_SESSION['logged_in']) {
header("Location: mainpage.php");
exit();
}
// Display login form
Upvotes: 0
Reputation: 3274
you can try this
JAVASCRIPT
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
HTML
<!--The page will refresh every 5 seconds.-->
<body onload="timedRefresh(5000)">
Upvotes: -1
Reputation: 45
<?php
session_start();
//all of the php code goes here
header("location: samepage.php")
?>
make sure your all code of php is at top level of your browser and not using any echo command - else you will end up showing something that is echo at the top of the page - instead of using echo command use variable that are more reliable then use variable in html body where necessary.
Upvotes: 1
Reputation: 7616
You can use any of them. However, header("location: abc.php")
will not work after sending response! The work around is simple. Use output buffering.
<?php
ob_start()
//here goes many lines of your wonderful php code blocks
//now send the header based on your logic
header("location: abc.php")
ob_end_flush()
Please check the official docs for more info
Update:
You can consider the suggestion of @zerkms. If you really need to silently redirect to other page, do that before sending any outputs using header()
function. However, if you want to show that you are redirecting him/her, you can use javascript as you were using! For the latter, you can also use Meta Refresh
<meta http-equiv="refresh" content="5;URL='http://example.com/'">
ob_start()
will be helpful for this. Because, you will probably show many things on the page and then tell that he/she will be redirected momentarily. The above example will redirect user to example.com in 5 seconds.
Upvotes: 1