提问者:小点点

$\会话存在,但为空。为什么?


我已经登录Mu用户(login.php)并开始会话,然后重定向到另一个页面(accueil.php)/

login.php:我的会话存在,我的cookie存在。在accueil.php:我的会话存在,我的cookie不存在。

==

==

或者

标题('位置:accueil.php');

==

我不明白。你有什么想法吗?!

这是我的代码:

登录。php:

    $username = $_GET['username'];
    $password = $_GET['password'];


    $sql = $connection->query("SELECT username, password FROM login WHERE username = '$username' && `password`= '$password';");
    while ($result = $sql->fetch()){
        $data = array('username' => $result['username'],
                      'password' => $result['password']);
    }
    try{
        if($data['username'] !== $username && $data['password'] !== $password )  {
            throw new Exception('Login incorrect', 500);
        }
        else{
            session_start();
            $_SESSION['username'] = $username;
            $_SESSION['password'] = $password;

            setcookie('maSession', $_SESSION['username'], time()+3600 , '/');
            header('Location: http://localhost/monsite/accueil.php');

        }
    }
    catch(Exception $e){
        header("HTTP/1.1 500 Internal Server Error");
        echo 'error: '.$e->getMessage();
    }

ccueil.php:"

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");

include_once('accueil.php');
require_once('db.php');

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    $connection = new PDO("mysql:host=$HOST;dbname=$DBNAME", $USER, $PASS);

    if(isset($_SESSION)) {
        $username = $_SESSION['username'];
        echo $username;
    }
    else{
        echo 'no session';
    }
}

-

-

非常感谢。


共1个答案

匿名用户

<?php
//Check session if not already started, then start it.
if(session_id() == '')
{
    session_start();
}

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");

include_once('accueil.php');
require_once('db.php');

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    $connection = new PDO("mysql:host=$HOST;dbname=$DBNAME", $USER, $PASS);
 
 // Check session 'username' it was not empty
    if(!empty($_SESSION['username'])) {
        $username = $_SESSION['username'];
        echo $username;
    }
    else{
        echo 'no session';
    }
}

?>