10

When I use php header redirection all session variables are lost... Some people say that adding exit(); just after the header(""); will solve the problem but it doesn't seem to be the solution...

Can anyone please help?

Here is how I store variable into the session:

include 'dbc.php';

$err = array();

foreach($_GET as $key => $value) {
    $get[$key] = filter($value); //get variables are filtered.
}

if ($_POST['doLogin']=='Login')
{

foreach($_POST as $key => $value) {
    $data[$key] = filter($value); // post variables are filtered
}


$user_email = $data['usr_email'];
$pass = $data['pwd'];


if (strpos($user_email,'@') === false) {
    $user_cond = "user_name='$user_email'";
} else {
      $user_cond = "user_email='$user_email'";

}


$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE 
           $user_cond
            AND `banned` = '0'
            ") or die (mysql_error()); 
$num = mysql_num_rows($result);

  // Match row found with more than 1 results  - the user is authenticated. 
    if ( $num > 0 ) { 

    list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);

    if(!$approved) {
    //$msg = urlencode("Account not activated. Please check your email for activation code");
    $err[] = "Account not activated. Please check your email for activation code";

    //header("Location: login.php?msg=$msg");
     //exit();
     }

        //check against salt
    if ($pwd === PwdHash($pass,substr($pwd,0,9))) { 
     // this sets session and logs user in  
       session_start();
       session_regenerate_id (true); //prevent against session fixation attacks.

       // this sets variables in the session 
        $_SESSION['user_id']= $id;  
        $_SESSION['user_name'] = $full_name;
        $_SESSION['user_level'] = $user_level;
        $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);

        //update the timestamp and key for cookie
        $stamp = time();
        $ckey = GenKey();
        mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());

        //set a cookie 

       if(isset($_POST['remember'])){
                  setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
                  setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
                  setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
                   }
        if(empty($err)){            
          header("Location: myaccount.php");
         }
        }
        else
        {
        //$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
        $err[] = "Invalid Login. Please try again with correct user email and password.";
        //header("Location: login.php?msg=$msg");
        }
    } else {
        $err[] = "Error - Invalid login. No such user exists";
      }     
}

Redirection code:

//connect database
    require_once 'dbc.php';

    page_protect();

    $authorID = $_SESSION['user_id'];
    if ( !empty($_POST["answ_content"]) && $authorID != 0 ) {
            //vaqciot html chveulebriv texad
            $content = htmlentities($_POST["answ_content"],ENT_COMPAT,'UTF-8');
            $dro = date('Y-m-d H:i:s');
            $qID = $_POST["question_ID"];
            $author = $_SESSION["user_name"];


            $sql="INSERT INTO wp_comments (comment_ID, comment_post_ID, comment_author, comment_author_IP, comment_date, comment_content, user_id) 
                VALUES
              (NULL, '$qID', '$author', '123.123.123.123', '$dro', '$content', '$authorID')";

            $result = mysql_query($sql);

            //pasuxebis raodenobis ertit gazrda
            $increase = "UPDATE wp_posts SET comment_count = comment_count+1 WHERE ID = $qID";
            mysql_query($increase);

            //gadamisamarteba shekitxvis gverdze  
            $url = 'Location:http://example.com/site/answ/question.php?ID=' .$qID;
            header($url);
    } else {
        echo 'error';
    }
King Julien
  • 10,981
  • 24
  • 94
  • 132

8 Answers8

11

You need to put exit(); after your header redirection, otherwise you have just loaded two pages of content into 1 page.

Also make sure you have session_start(); at the top of all your scripts.

Lizard
  • 43,732
  • 39
  • 106
  • 167
4

You aren't starting the session. In order to use session variables and have them carry across pages, you need to put

session_start();

at the top of each page before anything else.

Joseph
  • 1,988
  • 14
  • 21
2

I was trying to set the session id of my own using :

session_id('own_generated_session_id_string');

But as the documentation says, you have to use this before

session_start();

Using it after session_start(), clears the session parameters.

emreozdemir
  • 145
  • 6
1

Simples! make sure the page you are coming from (e.g. www.example.com) redirects to a (eg.g www.example.com/redirect.php) notice www at the beginning. If you change that from page to page, then yes things get wonky.

dvancouver
  • 723
  • 5
  • 14
  • 22
  • Same problem, header redirects were changing from page to page and i switched it to the common scheme used all across the project and voila, it worked.. screwed my ass over this for at least a week... thanks man, you are a saviour... – coder101 Nov 25 '13 at 15:27
0

These sessions does not always work as we expect sometimes. I had a similar problem with my website using sessions that get lost. I basically solved it by injecting the value I want to keep on the session into the hidden text field the first time the page loads. Then the second time I call the page(page submit) I simply read the value from the hidden text field and carry on with rest of my code.

That's more easier and cleaner than using sessions in this case!

0

exit; should be placed after header redirection or session_regenerate_id(true); can be used

Lovepreet Singh
  • 4,792
  • 1
  • 18
  • 36
0

You just need to check the file permission in /var/lib/php directory give yje public permisssion to /var/lib/php/session directory.

and all done.

Arvind
  • 1
  • 3
0
  • Include session_start(); in both the files before the session.
  • Note don't use session_destroy() in the redirected file.