Search code examples
phpmysqlsession-cookiessession-variablessession-state

Session variable was empty in php


login.php

    <?php
    ob_start();
    session_start();
    include '../config.php';
    if( (isset($_SESSION['can-id']) )) {
    header('location: ../home/profile.php');
    }
    if(isset($_POST['can-login']))
    {
        $email=$_POST['email'];
        $password=$_POST['password'];
    $sql="SELECT * FROM `user_credentials` WHERE `email`=:email AND `password`=:password";
    $pdoResult=$conn->prepare($sql);
    $pdoExec=$pdoResult->execute(array(":email"=>$email,":password"=>$password));
    $pdoResult->setFetchMode(PDO::FETCH_ASSOC);
    $count=0;
    $uid='';
    while ($r=$pdoResult->fetch()) {
      # code...
    $count+=1;
    $uid=$r['email'];
    }

    if ($count==1) {
      # code...
      $_SESSION['can-id']=$uid;
      header('location: ../home/profile.php');

    }
    else
    {
      $_SESSION['error']="login failed";
    }
    }
    ?>

<html>
....
</html>

profile.php

<?php
    ob_start();
    session_start();
    if (!(isset($_SESSION['can-id']))) {
        # code...
        header('location: ../login/');

    }
    else
    {
        $cid=$_SESSION['can-id'];
    }
?>
<h1 ><?php echo $cid;?></h1>

This is my code after log in the page was redirected to profile.php page but in profile page session variable doesn't printed I don't know why but this problem was not occuring every time I log in It occurs sometimes so I can't find what is the problem. Anyone knows please help me to solve the problem.


Solution

  • Remove ob_start() from your login.php Don't put session_start() in all of your file

     e.g login.php, profile.php, etc
    

    but instead, add this to your config.php for example:

    <?php 
     session_start(); 
     //.. config variables here
    

    Then, include config.php also in your profile.php.