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.
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.