Manoj
Manoj

Reputation: 13

Session isn't working in PHP

I am working on one code of login and user profile but I am facing problem with session. I want to do when user login through Login.php then it goes to User.php. But when I open this page in a new tab then it goes to Login.php and again asks for Login. Can anyone tell me where I am wrong? My code is below.

Login.Php

<?php 
session_start();
// check if session set.
if(isset($_SESSION['id'])) {
    $url=SITE_URL.'User.php';
   (header("Location: $url"));
}
?>

<?php 
include("dbconfig.php");
include('class/userClass.php');
$userClass = new userClass();

$errorMsgLogin='';
if (!empty($_POST['loginSubmit'])) 
{
$usernameEmail=$_POST['username'];
$password=$_POST['password'];
 if(strlen(trim($usernameEmail))>1 && strlen(trim($password))>1 )
   {
    $id=$userClass->userLogin($usernameEmail,$password);
    if($id)
    {
        $url=SITE_URL.'User.php';
        header("Location: $url");
    }
    else
    {
        $errorMsgLogin="Please check login details.";
    }
   }
}


?>
<!doctype html>
<html>
<head>
</head>
<body>
<form id="contact-form" method="post">
            <div class="login-controls">
                <div class="form-input">
                    <input type="text" class="txt-box"  name="username" id="username" placeholder="Username" required>
                </div>
                <div class="form-input">
                    <input type="password" class="txt-box" name="password" id="password" placeholder="Password" required>
                </div>
<div class="errorMsg"><?php echo $errorMsgLogin; ?></div>
                <div class="main-bg">
                    <input type="submit"  name="loginSubmit" id="submit" class="btn " value="Login">
                </div>
<div class="check-box">
                    <a href="ForgotPassword.php">Forgot your Password ?</a>
                </div>


</form>
</br></br>
</body>
</html>

User.php

 <?php
    session_start();

    // check if session set.
    if(!isset($_SESSION['id']) || empty($_SESSION['id'])) {
        $url=SITE_URL.'Login.php';
        die(header("Location: $url"));
    }
    ?>
    <?php
    $session_id=$_SESSION['id'];
    include('class/userClass.php');
    $userClass = new userClass();
    include('dbconfig.php');
    $userDetails=$userClass->userDetails($session_id);
    ?>

         <!doctype html>
            <html>
            <head>
            </head>
            <body>
          ------------something-----
                </body>
            </html>

dbconfig.php

<?php
session_start();
/* DATABASE CONFIGURATION */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'XXXXXX');
define('DB_PASSWORD', 'XX2');
define('DB_DATABASE', 'Xxxx');
define("SITE_URL", "http://try1234.com"); // Eg. http://yourwebsite.com


function getDB() 
{
    $dbhost=DB_SERVER;
    $dbuser=DB_USERNAME;
    $dbpass=DB_PASSWORD;
    $dbname=DB_DATABASE;
    try {
    $dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); 
    $dbConnection->exec("set names utf8");
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbConnection;
    }
    catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
    }

}
?>

userClass.php

<?php
    class userClass
    {
         /* User Login */
         public function userLogin($usernameEmail,$password)
         {

              $db = getDB();
              $hash_password= hash('sha256', $password);
              $stmt = $db->prepare("SELECT id FROM profile WHERE  username=:usernameEmail  AND  pass=:hash_password");  
              $stmt->bindParam("usernameEmail", $usernameEmail,PDO::PARAM_STR) ;
              $stmt->bindParam("hash_password", $hash_password,PDO::PARAM_STR) ;
              $stmt->execute();
              $count=$stmt->rowCount();
              $data=$stmt->fetch(PDO::FETCH_OBJ);
              $db = null;
              if($count)
              {
                    $_SESSION['id']=$data->id;
                    return true;
              }
              else
              {
                   return false;
              }    
         }

         /* User Details */
         public function userDetails($id)
         {
            try{
              $db = getDB();
              $stmt = $db->prepare("SELECT email,username,Pname, Mobile FROM profile WHERE id=:id");  
              $stmt->bindParam("id", $id,PDO::PARAM_INT);
              $stmt->execute();
              $data = $stmt->fetch(PDO::FETCH_OBJ);
              return $data;
             }
             catch(PDOException $e) {
              echo '{"error":{"text":'. $e->getMessage() .'}}'; 
              }

         }


    }

?>

Upvotes: 0

Views: 64

Answers (2)

chris g
chris g

Reputation: 1108

If you know you're going to need session availability on each page, you can edit your php.ini and add session.auto_start = 1, or you can do as the commenter above suggested and add session_start(); in each of your files (or use a base include containing session_start();)

Upvotes: 0

Darren
Darren

Reputation: 13128

As noted in the comments, if you want to use sessions on any page, you will always need to start the session.

This is usually done as the very first thing on each of those pages:

<?php
session_start();

//.....the rest of your code.

Evidentally, you will need to start it on your session.php page for it to work.

It's also worth noting that your session.php logic is a bit redundant. You'd be better off doing something similar to:

<?php
session_start();

// check if session set.
if(!isset($_SESSION['id']) || empty($_SESSION['id'])) {
    $url=SITE_URL.'Login.php';
    die(header("Location: $url"));
}
// otherwise continue.
include('class/userClass.php');
$userClass = new userClass();

//.... the rest of your code.

The above removes redundant/recursive checks if the session is present & allows proper code "flow".

Upvotes: 2

Related Questions