简体   繁体   中英

After checking session it is not redirecting to another page

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>

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM