PHP页面之间不保存$ _SESSION变量 [英] $_SESSION variable not saving between pages PHP

查看:76
本文介绍了PHP页面之间不保存$ _SESSION变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用登录系统将我的用户名保存到SESSION变量但不保存。

Im trying to save my username to the SESSION variable using a login system however it doesn't save.

我尝试在同一时间打印会话变量页面,但是当我去另一个页面时,它将无法保存。

I tried printing the session variable straight away in the same page and that works however when i go to another page, it won't save.

我是非常新的这个东西所以我很抱歉,如果这是显而易见的事情:)

I'm very new this stuff so im sorry if it's something obvious :)

任何帮助将不胜感激:)

Any help will be much appreciated :)

PHP代码1:

$app->post('/api/customer/login/{Username}/{PassW}', function(Request $request, Response $response){
    $Username = $request->getParam('Username');
    $PassW = $request->getParam('PassW');

    $PassW = md5($PassW);//FIND NEW WAY OF HASHING AS MD5 IS DEPRECIATED
    $sql = "SELECT * FROM login WHERE Username= '$Username' AND PassW='$PassW' LIMIT 1";

    try{
        $db = new db();
        $db = $db->connect();

        $stmt = $db->query($sql);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if(count($result) == 1){
        session_start();      
        $_SESSION['Username'] = $Username;

       echo "<script type='text/javascript'>alert('Correct!');
       window.location='http://localhost/testing/dashboard.php';
       </script>";
        exit();

PHP代码2(下一页):

PHP CODE 2 (The next page):

这个页面是一个简单的HTML页面,其它的东西却在它的正文中有下面的PHP代码来测试它是否保存了这个变量。

This page is simply a HTML page with other stuff but has the below PHP code in its body to test if its saved the variable.

<?php
        session_start(); 
        print_r($_SESSION);
  ?>


推荐答案

每当您在页面上使用会话时,您必须启动在那个页面上的会话,所以你的代码2页面上的代码应该是这样的

whenever you use session on the page so you must start the session on that page so your code on code 2 page should be like this

<?php
session_start();
print_r($ _ SESSION);
?>

此外,在登录页面上添加相同的行

also, add the same line on a login page

session_start();

如果一切似乎都正常,那么尝试从您的浏览器中删除缓存,因为您使用的是javascript重定向页面,浏览器可能会从缓存加载页面。

if everything seems fine to you then try to remove the cache from your browser as you are using javascript to redirect the page and there might be a chance that browser is loading the page from cache.

这篇关于PHP页面之间不保存$ _SESSION变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆