Reputation: 1816
Here is my code in which i am checking if session variable is not set then it will redirect to another page:
if (!isset($_SESSION)) {
session_start();
}
if (!isset($_SESSION['username']))
{
header("location: http://myweb.com/rel_notes/?page_id=779");
}
Problem: It is not redirecting to another page BUT if i change this line
header("location: http://myweb.com/rel_notes/?page_id=779");
to
die("You aren't allowed to access this page");
then it works. So Kindly tell me why it is not redirecting to another page?
EDIT: This is my whole code of that wordpress page im currently working on:
<?php
ob_start();
session_start();
if (!isset($_SESSION['username']))
{
header("location: http://myweb.com/rel_notes/?page_id=779");
exit();
}
if (isset($_POST["cancel"]))
{
if (!isset($_SESSION)) {
session_start();
}
session_unset();
session_destroy();
header("location: http://myweb.com/rel_notes/?page_id=779");
exit();
}
?>
<form method="post" enctype="multipart/form-data">
<div align="right">
<input class="btn btn-primary" type="submit" value="Log Out" name="cancel" id="cancel" style=""/>
</div>
</form>
Upvotes: 0
Views: 904
Reputation: 68476
Try like this. If this is just the code it will work fine.
<?php
session_start();
if (!isset($_SESSION['username']))
{
header("location: http://myweb.com/rel_notes/?page_id=779");
}
If you have any other code after this you may get headers already sent
notice.
EDIT :
You can even achieve this using JS. [However , I personally don't recommend]
<?php
session_start();
if (!isset($_SESSION['username']))
{
//header("location: http://myweb.com/rel_notes/?page_id=779");
echo "<script>document.location.href='http://myweb.com/rel_notes/?page_id=779'</script>";
exit;
}
Upvotes: 1
Reputation: 326
Is there any output above this code? header("location: ...");
works only if there was no output yet. If you need it nonetheless, add ob_start();
at the top of your script.
Upvotes: 1