php会话随机丢失,无法理解原因
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php会话随机丢失,无法理解原因相关的知识,希望对你有一定的参考价值。
我付了一个程序员来制作一个购物篮脚本来使用Spreadshirt API。一切都很完美,除了篮子一直在排空。我认为会话在某些时候丢失,所以脚本创建另一个BasketId
。
我试图找出它是否有特定原因发生,没有任何成功......我无法重现这个错误。它只是随机发生而没有任何理由。关闭浏览器,重置apache甚至整个网络服务器都不会引起会话丢失。
我有两个不同的脚本在同一个域上使用cookie,他们没有任何问题(一个是管理员登录会话的cookie,另一个cookie是保存用户在商店上最后查看的文章)
我尝试了谷歌上找到的所有解决方案没有任何成功:编辑php.ini
,通过php强制ini设置,尝试了htaccess
方式,...
这是我的phpinfo的“会话”部分:http://gyazo.com/168e2144ddd9ee368a05754dfd463021
shop-ajax.php
(会话处理@第18行)
ini_set('session.cookie_domain', '.mywebsite.com' );
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
$language = addslashes($_GET['l']);
$shopid = addslashes($_GET['shop']);
// if($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
// die("no direct access allowed");
// }
if(!session_id()) {
$lifetime=60 * 60 * 24 * 365;
$domain = ".mywebsite.com";
session_set_cookie_params($lifetime,"/",$domain);
@session_start();
}
// Configuration
$config['ShopSource'] = "com";
$config['ShopId'] = $shopid;
$config['ShopKey'] = "*****";
$config['ShopSecret'] = "*****";
/*
* add an article to the basket
*/
if (isset($_POST['size']) && isset($_POST['appearance']) && isset($_POST['quantity'])) {
/*
* create an new basket if not exist
*/
if (!isset($_SESSION['basketUrl'])) {
/*
* get shop xml
*/
$stringApiUrl = 'http://api.spreadshirt.'.$config['ShopSource'].'/api/v1/shops/' . $config['ShopId'];
$stringXmlShop = oldHttpRequest($stringApiUrl, null, 'GET');
if ($stringXmlShop[0]!='<') die($stringXmlShop);
$objShop = new SimpleXmlElement($stringXmlShop);
if (!is_object($objShop)) die('Basket not loaded');
/*
* create the basket
*/
$namespaces = $objShop->getNamespaces(true);
$basketUrl = createBasket('net', $objShop, $namespaces);
$_SESSION['basketUrl'] = $basketUrl;
$_SESSION['namespaces'] = $namespaces;
/*
* get the checkout url
*/
$checkoutUrl = checkout($_SESSION['basketUrl'], $_SESSION['namespaces']);
// basket language workaround
if ($language=="fr") {
if (!strstr($checkoutUrl,'/fr')) {
$checkoutUrl = str_replace("spreadshirt.com","spreadshirt.com/fr",$checkoutUrl);
}
}
$_SESSION['checkoutUrl'] = $checkoutUrl;
}
/*
Workaround for not having the appearance id :(
*/
if ($_POST['appearance']==0) {
$stringApiArticleUrl = 'http://api.spreadshirt.'.$config['ShopSource'].'/api/v1/shops/' . $config['ShopId'].'/articles/'.intval($_POST['article']).'?fullData=true';
$stringXmlArticle = oldHttpRequest($stringApiArticleUrl, null, 'GET');
if ($stringXmlArticle[0]!='<') die($stringXmlArticle);
$objArticleShop = new SimpleXmlElement($stringXmlArticle);
if (!is_object($objArticleShop)) die('Article not loaded');
$_POST['appearance'] = intval($objArticleShop->product->appearance['id']);
}
/*
* article data to be sent to the basket resource
*/
$data = array(
'articleId' => intval($_POST['article']),
'size' => intval($_POST['size']),
'appearance' => intval($_POST['appearance']),
'quantity' => intval($_POST['quantity']),
'shopId' => $config['ShopId']
);
/*
* add to basket
*/
addBasketItem($_SESSION['basketUrl'] , $_SESSION['namespaces'] , $data);
$basketData = prepareBasket();
echo json_encode(array("c" => array("u" => $_SESSION['checkoutUrl'],"q" => $basketData[0],"l" => $basketData[1])));
}
// no call, just read basket if not empty
if (isset($_GET['basket'])) {
if (array_key_exists('basketUrl',$_SESSION) && !empty($_SESSION['basketUrl'])) {
$basketData = prepareBasket();
echo json_encode(array("c" => array("u" => $_SESSION['checkoutUrl'],"q" => $basketData[0],"l" => $basketData[1])));
} else {
echo json_encode(array("c" => array("u" => "","q" => 0,"l" => "")));
}
}
function prepareBasket() {
$intInBasket=0;
if (isset($_SESSION['basketUrl'])) {
$basketItems=getBasket($_SESSION['basketUrl']);
if(!empty($basketItems)) {
foreach($basketItems->basketItems->basketItem as $item) {
$intInBasket += $item->quantity;
}
}
}
$l = "";
$pQ = parse_url($_SESSION['checkoutUrl']);
if (preg_match("#^basketId=([0-9a-f-])*$#i", $pQ['query'])) {
$l = $pQ['query'];
}
return array($intInBasket,$l);
}
// Additional functions
function addBasketItem($basketUrl, $namespaces, $data) {
global $config;
$basketItemsUrl = $basketUrl . "/items";
$basketItem = new SimpleXmlElement('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<basketItem xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://api.spreadshirt.net">
<quantity>' . $data['quantity'] . '</quantity>
<element id="' . $data['articleId'] . '" type="sprd:article" xlink:href="http://api.spreadshirt.'.$config['ShopSource'].'/api/v1/shops/' . $data['shopId'] . '/articles/' . $data['articleId'] . '">
<properties>
<property key="appearance">' . $data['appearance'] . '</property>
<property key="size">' . $data['size'] . '</property>
</properties>
</element>
<links>
<link type="edit" xlink:href="http://' . $data['shopId'] .'.spreadshirt.' .$config['ShopSource'].'/-A' . $data['articleId'] . '"/>
<link type="continueShopping" xlink:href="http://' . $data['shopId'].'.spreadshirt.'.$config['ShopSource'].'"/>
</links>
</basketItem>');
$header = array();
$header[] = createAuthHeader("POST", $basketItemsUrl);
$header[] = "Content-Type: application/xml";
$result = oldHttpRequest($basketItemsUrl, $header, 'POST', $basketItem->asXML());
}
function createBasket($platform, $shop, $namespaces) {
$basket = new SimpleXmlElement('<basket xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://api.spreadshirt.net">
<shop id="' . $shop['id'] . '"/>
</basket>');
$attributes = $shop->baskets->attributes($namespaces['xlink']);
$basketsUrl = $attributes->href;
$header = array();
$header[] = createAuthHeader("POST", $basketsUrl);
$header[] = "Content-Type: application/xml";
$result = oldHttpRequest($basketsUrl, $header, 'POST', $basket->asXML());
$basketUrl = parseHttpHeaders($result, "Location");
return $basketUrl;
}
function checkout($basketUrl, $namespaces) {
$basketCheckoutUrl = $basketUrl . "/checkout";
$header = array();
$header[] = createAuthHeader("GET", $basketCheckoutUrl);
$header[] = "Content-Type: application/xml";
$result = oldHttpRequest($basketCheckoutUrl, $header, 'GET');
$checkoutRef = new SimpleXMLElement($result);
$refAttributes = $checkoutRef->attributes($namespaces['xlink']);
$checkoutUrl = (string)$refAttributes->href;
return $checkoutUrl;
}
/*
* functions to build headers
*/
function createAuthHeader($method, $url) {
global $config;
$time = time() *1000;
$data = "$method $url $time";
$sig = sha1("$data ".$config['ShopSecret']);
return "Authorization: SprdAuth apiKey="".$config['ShopKey']."", data="$data", sig="$sig"";
}
function parseHttpHeaders($header, $headername) {
$retVal = array();
$fields = explode("
", preg_replace('/x0Dx0A[x09x20]+/', ' ', $header));
foreach($fields as $field) {
if (preg_match('/(' . $headername . '): (.+)/m', $field, $match)) {
return $match[2];
}
}
return $retVal;
}
function getBasket($basketUrl) {
$header = array();
$basket = "";
if (!empty($basketUrl)) {
$header[] = createAuthHeader("GET", $basketUrl);
$header[] = "Content-Type: application/xml";
$result = oldHttpRequest($basketUrl, $header, 'GET');
$basket = new SimpleXMLElement($result);
}
return $basket;
}
function oldHttpRequest($url, $header = null, $method = 'GET', $data = null, $len = null) {
switch ($method) {
case 'GET':
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
if (!is_null($header)) curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
break;
case 'POST':
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true); //not createBasket but addBasketItem
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
break;
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>
脚本中还有另外两个部分:一个用于向篮子(example.php)
添加样本T恤的表单和一个用于调用ajax (shop-controller.js)
的脚本。如果需要可以发布,但没有会话处理的东西。
更新 - 可能问题与会话无关。 BasketId丢失,但PHPSESSID在浏览器cookie中保持不变。
我在过去3天内进行了以下测试(使用不同的计算机和浏览器进行测试):
- 清空浏览器cookie然后在下午开始新的会话
- 将1项添加到购物篮,我写下BasketId并检查浏览器cookie以记下PHPSESSID
- 通常总是在午夜左右,篮子自己空了
- PHPSESSID在我的浏览器cookie中保持不变,即使篮子本身空了
- 但是BASKETID不一样,下午使用的BASKETID丢失了,重新生成了一个新的
服务器是CentOS 5.9 - PHP版本5.2.9(来自OVH)。专用IP上的专用服务器。
首先,您需要查找问题是在会话的垃圾收集中还是在代码中出现逻辑错误。为此,您可以:
// Add this right after session_start()
if (!isset($_SESSION['mySessionCheck'])) {
$_SESSION['mySessionCheck'] = "This session (" . session_id() . ") started " . date("Y-m-d H:i:s");
}
// For html pages, add this:
echo '<!-- ' . $_SESSION['mySessionCheck'] . ' -->';
// For AJAX pages, add "mySessionCheck" to the JSON response:
echo json_encode(
array(
"c" => array(
"u" => $_SESSION['checkoutUrl'],
"q" => $basketData[0],
"l" => $basketData[1]
),
"mySessionCheck" => $_SESSION['mySessionCheck']
)
);
如果此消息在篮子清空的同时发生变化,那么您将确定PHP会话存在问题。
在这种情况下,您可以尝试以下几种方法:
1)你在做
$lifetime=60 * 60 * 24 * 365;
$domain = ".mywebsite.com";
session_set_cookie_params($lifetime,"/",$domain);
@session_start();
但根据PHP.net docs的user contributed note:
使用
session_set_cookie_params()
时,PHP的会话控制无法正确处理会话生存期。
所以你可以尝试使用setcookie()
代替:
$lifetime=60 * 60 * 24 * 365;
session_start();
setcookie(session_name(),session_id(),time()+$lifetime);
即使它是评论中指出的一个4岁的音符,我测试了它仍然发生(我在PHP 5.5.7,Windows Server 2008,IIS / 7.5)。只有setcookie()
生成了HTTP标头来更改过期日期(示例设置$lifetime
为600):
Set-Cookie: PHPSESSID=(the id); expires=Mon, 22-Jun-2015 15:03:17 GMT; Max-Age=600
2)如果您使用的是Debian服务器或某些衍生产品,他们会使用use a cron job to clear out PHP sessions,因此您可以尝试:
3)要确定是否有某些进程清除会话,您可以将监视放在存储会话文件的目录中(实际路径因服务器而异,请使用session_save_path
查找您的位置)。我不是服务器管理员,但我读过你可以使用auditctl
,只需确保你记录who made the changes to your files。
4)如果您无权访问服务器配置,或者不想依赖服务器配置(如果切换主机,则很好),您可以实现自己的会话处理程序。看看这个example by Pedro Gimeno。
您只将@session_start();
放在所有脚本的顶部。
还放在你的ajax脚本的顶部。
示例如下:
@session_start();
// you may use session script here or header file
include("header.php");
//some code. you may use session script here or header file
include("main.php");
//-----------next code
我在这里发帖,即使是旧帖子,万一有人遇到这个问题,请查看php.ini session.gc_maxlifetime,或打印ini_get('session.gc_maxlifetime');你必须在你的php脚本或php.ini中设置它,在我的php版本上默认是1440秒,我已经将它改为1个月,在我的情况下已经足够了。在启动会话之后,你可以setcookie(session_name(),session_id(),time()+ $ sessionLifetime,“”,“”,false,true);我希望这有帮助。
以上是关于php会话随机丢失,无法理解原因的主要内容,如果未能解决你的问题,请参考以下文章