简体   繁体   中英

My PHP Session variables not working in another page when we redirect that page and write session_start(); function

I want to use session variables in some pages but when i used then not work in another page, I also used session_start() function.

<?php
    session_start();
    $mobile = $_POST['mobile'];
    $password = $_POST['password'];
    $host ="localhost";
    $dbUsername ="jmpcompu_admin";
    $dbPassword = "Jmpcompu@";
    $dbname= "jmpcompu_member";
    $conn = mysqli_connect($host, $dbUsername, $dbPassword, $dbname);
    if (!$conn) {
       die("Connection failed: " . mysqli_connect_error());
    }
    mysqli_select_db($conn,$dbname);
    $sql = "SELECT id,name,mobile, password FROM register WHERE mobile =".$mobile;
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    if($row["mobile"]==$mobile && $row["password"]==$password)
    {
       $_SESSION["user_id"] = $row["id"];
       $_SESSION["username"] = $row["name"];
       echo "You are a validated user. Click on button for Papers...";
        echo '<input type="button" value="RSCIT Online Papers" onclick="window.location=\'/web2/StudyMaterial.php\'" />';
    }
    else
    {
       echo"Sorry, your credentials are not valid, Please try again.";
       echo '<input type="button" value="Please Try Again !!" onclick="window.location=\'http://jmpcomputer.in/web2/loginrscit.html\'" />';
    }
    mysqli_close($conn);
?>

Studymaterial.php

<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
$uname = $_SESSION["username"];
$id = $_SESSION["user_id"];
echo $_SESSION["username"];
echo $_SESSION["user_id"];
echo $uname;
echo $id;
?>

Nothing come in output One time it shows result but after that it does not show.

You don't have to check if an existing session already exists or not because:

session_start(): start new session or resume existing session replace this:

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

by only : session_start();

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