php 会话变量在页面加载之间不持久

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6200612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:38:29  来源:igfitidea点击:

Session variables are not persisting between page loads

phpsession-variables

提问by user520300

Can someone tell me why the session vars are not passing between pages? They were working up to 2 days ago. Now its not? There is a third party system that logs users in based on the third party system. I direct users to the login page with the return url. The third party system logs a user in and passes their id and a token generated on their end and returns them to my site with the id and the token in the url.

有人能告诉我为什么会话变量没有在页面之间传递吗?他们一直工作到 2 天前。现在不是?有一个第三方系统,可以在第三方系统的基础上进行用户登录。我使用返回 url 将用户引导到登录页面。第三方系统让用户登录并传递他们的 id 和在他们端生成的令牌,然后将它们与 id 和 url 中的令牌一起返回到我的站点。

If sessions are not set i try and grab the id and the token from the url and set the sessions. (working) I then generate my own token to validate against the token passed from the third party system (working) when i go to click to another page the sessions i set are not empty (????)

如果未设置会话,我会尝试从 url 中获取 id 和令牌并设置会话。(工作)然后我生成自己的令牌以验证从第三方系统(工作)传递的令牌,当我点击另一个页面时,我设置的会话不为空(????)

Here is my code:

这是我的代码:

    <?php
    session_start();

    // FUNCTION TO PASS THE URL THE USER IS ON SO THEY COME 
    // BACk TO THIS PAGE AFTER THE LOG IN. IF APPLICABLE
    function curPageURL() {
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    } else {
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $pageURL;
    }

    // DESTROY SESSION INFO IF TIMED OUT
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    session_destroy();   // destroy session data in storage
    session_unset();     // unset $_SESSION variable for the runtime
    }

    // SET THE SESSIONS WITH INFO PASSED FROM
    // LOGIN PAGE SENT AS A GET
    if(isset($_SESSION['ID']) && isset($_SESSION['token'])) {}else{
    $_SESSION['ID'] = $_GET['ID'];
    $_SESSION['token'] = $_GET['token'];
    }

    // GENERATE MY TOKEN TO MATCH THE LOGIN SYSTEM TOKEN
    $userIP = $_SERVER['REMOTE_ADDR'];
    $secretkey = 'A Unique Key For The Logged In User Matching the Login System Passed From mydomain.com/login.php';
    $algorithm = 'md5';
    $mm = date('m');
    $dd = date('d');
    $mmdd = $mm.$dd;
    $mytoken = strtoupper(hash($algorithm, $secretkey.$_SESSION['ID'].$userIP.$mmdd));


    $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
    // THIS IS WHERE THINGS ARE GOING WRONG
// SESSION token IS NO LONG SET AFTER I Go To another page
// and my token isnt the same any more either because session ID
// is no longer set???
    if($_SESSION['token']==$mytoken){}else{
    header("location: https://mydomain.com/login.php?returnURL=".curPageURL());
    }
    ?>

ok this is messed up. It has to be a problem on the hosting providers PHP setup i think because i created two pages. one called info with this code:

好吧,这搞砸了。我认为这一定是托管服务提供商 PHP 设置的问题,因为我创建了两个页面。使用此代码调用信息:

<?
session_start();

$_SESSION['ID'] = "112233";
$_SESSION['token'] = "mytoken";

print $_SESSION['ID'];
print $_SESSION['token'];
?>
<a href="info2.php">info 2</a>

and one called info2 with this code:

还有一个叫做 info2 的代码如下:

<?
session_start();

print $_SESSION['ID'];
print $_SESSION['token'];
?>
<a href="info.php">info</a>

info created and printed the session ok. when i click the link to go to info2 the sessions dont print. Is this a hosting config problem?

信息创建并打印会话确定。当我单击链接转到 info2 时,会话不会打印。这是主机配置问题吗?

采纳答案by user520300

The answer to this is it was a hosting configuration error. Hosting company changed something and it has worked ever since.

答案是这是一个托管配置错误。托管公司改变了一些东西,从那以后它一直有效。

回答by Rudi Visser

As already mentioned, ensure you're calling session_start()on each page.

如前所述,确保您session_start()在每个页面上都调用。

Additionally, are the scripts on different subdomains?? If they are you should set the INI value session.cookie_domainto .DOMAIN.EXT.

另外,脚本是否在不同的子域上??如果是,您应该将 INI 值设置session.cookie_domain.DOMAIN.EXT.

To further debug this whole situation, do some simple cookie watching. See if PHPSESSIDis present as a cookie on both page requests, if it's not then this is your problem. You can't store cookies cross-domain unless you reconstruct them.

为了进一步调试整个情况,做一些简单的 cookie 观察。查看是否PHPSESSID在两个页面请求中都作为 cookie 存在,如果不是,则这是您的问题。除非您重建它们,否则您无法跨域存储 cookie。



In response to your update, try doing this underneath your call to session_start():

为了响应您的更新,请尝试在您的调用下执行此操作session_start()

echo session_id();

Confirm that it's the same on both pages. If not, check the value of session.cookie_domainlike this:

确认两个页面上的内容相同。如果没有,请检查这样的值session.cookie_domain

echo ini_get('session.cookie_domain');

Is that set to anything? By default it should be blank, if it's set, especially not to your domain, this is the problem.

那是设置什么吗?默认情况下它应该是空白的,如果它被设置,特别是不是你的域,这就是问题所在。

You can also try debugging the cookie value of PHPSESSIDlike I first suggested.

您也可以尝试调试PHPSESSID我最初建议的 cookie 值。

回答by Jagadeesan

Check List
1. Make sure that you have used session_start(); in the next page.

2. Are you using .htaccess file?
    if so remove the .htaccess file and check the same.
    some time rewrite rules cause session probs...

3. If session is working fine and you have trouble only with token, then check the token sent in url is url_encoded.

检查清单
1. 确保您已使用 session_start(); 在下一页。

2. 你在使用 .htaccess 文件吗?
    如果是这样,请删除 .htaccess 文件并检查相同内容。
    有时重写规则会导致会话问题...

3. 如果会话工作正常并且您只有令牌有问题,则检查 url 中发送的令牌是否为 url_encoded。

回答by Hemant Jadhav

it's not the hosting server issue...

这不是托管服务器的问题...

check your URLs

检查您的网址

if a user is login under "example.com" session will be stored for "example.com" and not "WWW.example.com" so if a link goes to www.example.com it will not have that session.

如果用户在“example.com”下登录,会话将存储为“example.com”而不是“WWW.example.com”,因此如果链接转到 www.example.com,它将没有该会话。

you can use htaccess to always set the url to "WWW.example.com" use below code for it

您可以使用 htaccess 始终将 url 设置为“WWW.example.com” 使用下面的代码

RewriteEngine On

重写引擎开启

RewriteCond %{HTTP_HOST} ^hemantjadhav.com$ [NC]

RewriteCond %{HTTP_HOST} ^hemantjadhav.com$ [NC]

RewriteRule ^(.*)$ http://www.hemantjadhav.com/$1 [L,R=301]

重写规则 ^(.*)$ http://www.hemantjadhav.com/$1 [L,R=301]

(replace hemantjadhav with your domain name)

(用您的域名替换 hemantjadhav)

回答by grayob

Check the size of the session file: (code taken from this post)

检查会话文件的大小:(代码取自这篇文章

$sessionfile = ini_get('session.save_path') . '/' . 'sess_'.session_id();  
echo 'session file: ', $sessionfile, ' ';  
echo 'size: ', filesize($sessionfile), "\n";

If your session file has zero size, make sure there is still disk space available on your server. That was the problem I had.

如果您的会话文件大小为零,请确保您的服务器上仍有可用的磁盘空间。这就是我遇到的问题。

Check disk space with df -hon a linux server.

检查df -hlinux 服务器上的磁盘空间。

回答by D.Sari

In my case the solution was to have different parameter names in $_GET and $_SESSION.

就我而言,解决方案是在 $_GET 和 $_SESSION 中使用不同的参数名称。

$_SESSION["businessid"] = $_GET["businessid"]; // Leads to problems with session.$_SESSION["business_id"] = $_GET["businessid"]; //Works perfectly.

$_SESSION["businessid"] = $_GET["businessid"]; // Leads to problems with session.$_SESSION["business_id"] = $_GET["businessid"]; //Works perfectly.

It sounds strange but that's my experience.

这听起来很奇怪,但这是我的经验。

回答by eldhose

The only answer for this problem is to use session_start();on the top of every page. It will work fine. Else you might need to contact your hosting provider about this problem.

这个问题的唯一答案是session_start();在每个页面的顶部使用。它会正常工作。否则,您可能需要就此问题联系您的托管服务提供商。

回答by Garrick Crouch

I had session.cookie_samesite = "Strict"in my runtime file and was trying to bounce my user from Oauth2.0 back to my site and the PHP session ID was getting erased when the redirects hit. I removed this from my runtime file and it works fine now.

我有session.cookie_samesite = "Strict"我的运行时文件,并试图将我的用户从 Oauth2.0 退回到我的网站,当重定向命中时,PHP 会话 ID 被删除。我从我的运行时文件中删除了它,现在它工作正常。

回答by bpile

I would add that I got caught up with the same problem, except that in my case page was behind Varnishcaching proxy and I missed out that configuration had a line where cookies were allowed only on specific paths, otherwise they would get removed with the following directive:

我想补充一点,我遇到了同样的问题,除了在我的情况下页面在Varnish缓存代理后面,我错过了配置中有一行只允许在特定路径上使用 cookie,否则它们将被删除以下内容指示:

unset req.http.cookie;

unset req.http.cookie;

Dont forget to also check your proxy settings.

不要忘记检查您的代理设置

回答by user3225121

Make sure both pages are on the same domain. Even www.site.com is different than site.com

确保两个页面都在同一个域中。甚至 www.site.com 也不同于 site.com