php转https,在PHP中从HTTP切换到HTTPS时会话丢失

在同一服务器上的HTTP和HTTPS服务之间切换时,您的HTTP会话ID不会传递到HTTPS会话。您可以通过以下三种方式之一将会话ID从HTTP页面传递到HTTPS页面来进行设置:

来自PHP:session_start:

session_start() 根据通过请求传递的当前会话ID(例如GET,POST或cookie)创建会话或恢复当前会话

当您使用会话时,通常会启动脚本session_start()。如果浏览器设置了会话ID cookie,session_start()则将使用该会话ID。如果浏览器没有设置会话ID cookie,session_start()则会创建一个新的cookie 。

如果未设置会话ID(在您的示例中,浏览器正在为HTTPS会话创建新的会话ID cookie),则可以使用该session_id()功能进行设置。session_id()还可以方便地将会话ID作为字符串返回。所以

...

$currentSessionID = session_id();

...

将$currentSessionID变量设置为等于当前会话ID,和

...

session_id($aSessionID);

...

将浏览器中的sessionID cookie设置为$aSessionID。来自PHP:session_id

这是一个包含两个脚本的示例。一个通过HTTP访问,另一个通过HTTPS访问。它们必须位于同一服务器上才能维护会话数据。

脚本1(HTTP):

// This script will create a session and display a link to your secure server address

// to transfer your session ID. In this example, the secure page to receive the session

// ID is located at http://www.yoursite.com/safePages/securePage.php

// Start a session using the current session ID stored in a cookie, or create

// a new session if none is set.

session_start();

$currentSessionID = session_id();

// Set a variable that will be retrieved with the HTTPS script.

$_SESSION['testvariable'] = 'It worked';

// $secureServerDomain is the domain of your secure server

$secureServerDomain = 'www.yoursite.com';

// $securePagePath is the path to the page that will receive and set the session ID.

$securePagePath = '/safePages/securePage.php'

echo 'Click here to transfer your session to the secure server';

?>

脚本2(HTTPS):

// Retrieve the session ID as passed via the GET method.

$currentSessionID = $_GET['session'];

// Set a cookie for the session ID.

session_id($currentSessionID);

// Start a session.

session_start();

// Test retrieval of variable set when using HTTP.

if (!empty($_SESSION['testvariable'])) {

echo $_SESSION['testvariable'];

} else {

echo 'It did not work.';

}

?>

为此,HTTP和HTTPS服务器必须使用相同的会话数据存储基板(即对于默认文件处理程序,在具有相同php.ini的同一物理机器上运行)。这里存在一些安全漏洞,因此我不会使用此代码来传输敏感信息。它只是一个可行的例子。

当我遇到这个问题之前,我想出了上面的快速修复,但我只记得问题的原因。我从http://www.example.com/page.php转到https://example.com/page.php(注意缺少“www”)。请确保http://www.example.com/page.php将链接到https://www.example.com/page.php,并且http://example.com将链接到https://example.com /page.php。

PS,我实际上并没有运行这些脚本,所以可能会有一两个错误,导致它们无法正常运行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值