php会话随机丢失,无法理解为什么 [英] php session is randomly lost and cant understand why

查看:45
本文介绍了php会话随机丢失,无法理解为什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花钱请了一个程序员来制作一个购物篮脚本来使用 Spreadshirt API.一切正常,除了篮子不断清空.我认为会话在某个时候丢失了,所以脚本创建了另一个 BasketId.

我试图找出发生这种情况的具体原因,但没有成功……我无法重现该错误.它只是随机发生,没有任何原因.关闭浏览器、重置 apache 甚至整个网络服务器都不会导致会话丢失.

我有两个不同的脚本在同一个域中使用 cookie,它们没有任何问题(一个是用于管理员登录会话的 cookie,另一个 cookie 用于保存用户上次查看的商店文章)

我尝试了在谷歌上找到的所有解决方案都没有成功:编辑 php.ini ,通过 php 强制设置 ini,尝试了 htaccess 方式,...

这是我的 phpinfo 的会话"部分:http://gyazo.com/168e2144ddd9ee368a05754dfd46302>

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 = addlashes($_GET['l']);$shopid = addedlashes($_GET['shop']);//if($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {//die("不允许直接访问");//}如果(!session_id()){$lifetime=60 *​​ 60 * 24 * 365;$domain = ".mywebsite.com";session_set_cookie_params($lifetime,"/",$domain);@session_start();}//配置$config['ShopSource'] = "com";$config['ShopId'] = $shopid;$config['ShopKey'] = "*****";$config['ShopSecret'] = "*****";/** 将文章添加到购物篮*/if (isset($_POST['size']) &&isset($_POST['appearance']) &&isset($_POST['quantity'])) {/** 如果不存在,则创建一个新篮子*/如果 (!isset($_SESSION['basketUrl'])) {/** 获取店铺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('篮子未加载');/** 创建篮子*/$namespaces = $objShop->getNamespaces(true);$basketUrl = createBasket('net', $objShop, $namespaces);$_SESSION['basketUrl'] = $basketUrl;$_SESSION['namespaces'] = $namespaces;/** 获取结帐网址*/$checkoutUrl = checkout($_SESSION['basketUrl'], $_SESSION['namespaces']);//篮子语言解决方法如果($语言==fr"){如果 (!strstr($checkoutUrl,'/fr')) {$checkoutUrl = str_replace("spreadshirt.com","spreadshirt.com/fr",$checkoutUrl);}}$_SESSION['checkoutUrl'] = $checkoutUrl;}/*没有外观 ID 的解决方法:(*/如果($_POST['外观']==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('文章未加载');$_POST['appearance'] = intval($objArticleShop->product->appearance['id']);}/** 要发送到购物篮资源的文章数据*/$数据=数组('文章ID' =>intval($_POST['文章']),'尺寸' =>intval($_POST['size']),'外观' =>intval($_POST['外观']),'数量' =>intval($_POST['数量']),'shopId' =>$config['ShopId']);/** 添加到购物车*/addBasketItem($_SESSION['basketUrl'] , $_SESSION['namespaces'] , $data);$basketData = prepareBasket();echo json_encode(array("c" => array("u" => $_SESSION['checkoutUrl'],"q" => $basketData[0],"l" => $basketData[1])));}//不调用,如果不为空就读取篮子如果 (isset($_GET['basket'])) {如果 (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])));} 别的 {echo json_encode(array("c" => array("u" => "","q" => 0,"l" => "")));}}函数prepareBasket() {$intInBasket=0;如果(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['查询'];}返回数组($intInBasket,$l);}//附加功能函数 addBasketItem($basketUrl, $namespaces, $data) {全局 $config;$basketItemsUrl = $basketUrl ./项目";$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"><数量>'.$data['数量'] .'</数量><element id="' . $data['articleId'] . '" type="sprd:article" xlink:href="http://api.spreadshirt.'.$config['ShopSource'].'/api/v1/shops/' . $data['shopId'] . '/articles/' . $data['articleId'] . '"><属性><property key="外观">'.$data['外观'] .'</属性><property key="size">'.$data['size'] .'</属性></属性></元素><链接><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'].'"/></链接></basketItem>');$header = 数组();$header[] = createAuthHeader("POST", $basketItemsUrl);$header[] = "内容类型:应用程序/xml";$result = oldHttpRequest($basketItemsUrl, $header, 'POST', $basketItem->asXML());}函数 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'] . '"/></篮子>');$attributes = $shop->baskets->attributes($namespaces['xlink']);$basketsUrl = $attributes->href;$header = 数组();$header[] = createAuthHeader("POST", $basketsUrl);$header[] = "内容类型:应用程序/xml";$result = oldHttpRequest($basketsUrl, $header, 'POST', $basket->asXML());$basketUrl = parseHttpHeaders($result, "位置");返回 $basketUrl;}功能结帐($basketUrl,$namespaces){$basketCheckoutUrl = $basketUrl ./查看";$header = 数组();$header[] = createAuthHeader("GET", $basketCheckoutUrl);$header[] = "内容类型:应用程序/xml";$result = oldHttpRequest($basketCheckoutUrl, $header, 'GET');$checkoutRef = new SimpleXMLElement($result);$refAttributes = $checkoutRef->attributes($namespaces['xlink']);$checkoutUrl = (string)$refAttributes->href;返回 $checkoutUrl;}/** 建立头文件的函数*/函数 createAuthHeader($method, $url) {全局 $config;$time = time() *1000;$data = "$method $url $time";$sig = sha1("$data ".$config['ShopSecret']);return "Authorization: SprdAuth apiKey=\"".$config['ShopKey']."\", data=\"$data\", sig=\"$sig\"";}函数 parseHttpHeaders($header, $headername) {$retVal = array();$fields =explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));foreach($fields 作为 $field) {if (preg_match('/(' . $headername . '): (.+)/m', $field, $match)) {返回 $match[2];}}返回 $retVal;}函数 getBasket($basketUrl) {$header = 数组();$basket = "";如果(!空($basketUrl)){$header[] = createAuthHeader("GET", $basketUrl);$header[] = "内容类型:应用程序/xml";$result = oldHttpRequest($basketUrl, $header, 'GET');$basket = new SimpleXMLElement($result);}返回 $basket;}function oldHttpRequest($url, $header = null, $method = 'GET', $data = null, $len = null) {开关($方法){案例获取":$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);休息;案例'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);//不是createBasket而是addBasketItemcurl_setopt($ch, CURLOPT_POSTFIELDS, $data);休息;}$result = curl_exec($ch);curl_close($ch);返回 $result;}?>

脚本还有另外 2 个部分:一个将示例 T 恤添加到购物篮的表单 (example.php) 和一个调用 ajax 的脚本 (shop-controller.js).如果需要,可以发布它,但没有会话处理的东西.

update - 也许问题与会话无关.BasketId 丢失,但 PHPSESSID 在浏览器 cookie 中保持不变.

过去 3 天我做了以下测试(在不同的计算机和浏览器上测试):

服务器是 CentOS 5.9 - PHP 版本 5.2.9(来自 OVH).专用 IP 上的专用服务器.

首先你需要找出问题是在 session 的垃圾回收还是代码中的逻辑错误.为此,您可以:

//在 session_start() 之后添加这个如果 (!isset($_SESSION['mySessionCheck'])) {$_SESSION['mySessionCheck'] = "此会话 (" . session_id() . ") 已开始" .date("Y-m-d H:i:s");}//对于 HTML 页面,添加以下内容:回声 '<!-- ' .$_SESSION['mySessionCheck'] .'-->';//对于 AJAX 页面,在 JSON 响应中添加mySessionCheck":回声 json_encode(大批(c"=>大批(你"=>$_SESSION['checkoutUrl'],q" =>$basketData[0],我"=>$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 文档:

<块引用>

PHP 的会话控制在使用 session_set_cookie_params() 时不能正确处理会话生存期.

所以你可以尝试使用 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=(id);到期=格林威治标准时间 2015 年 6 月 22 日星期一 15:03:17;最大年龄=600

2) 如果您使用的是 Debian 服务器或某些衍生产品,它们 使用 cron 作业清除 PHP 会话,因此您可以尝试:

3) 要查看是否有清除会话的进程,您可以监视会话文件的存储目录(实际路径因服务器而异,请使用 session_save_path 以找出您的位置).我不是服务器管理员,但我读过你可以使用 auditctl 为此,只需确保您登录 谁对您的文件进行了更改.

4) 如果您无权访问服务器配置,或者不想依赖服务器配置(如果切换主机很好),您可以实现自己的会话处理程序.看看这个 Pedro Gimeno 的例子.>

I paid a programmer to make a shop basket script to work with Spreadshirt API. Everything is working perfectly, except that the basket keeps emptying itself. I think the session is lost at some point so the script creates another BasketId.

I tried to find if there was a specific reason it was happening, without any success... I can't reproduce the bug. It just happens randomly without any reason. Closing the browser, resetting apache or even the whole webserver won't provoke session lost.

I've got two different scripts working with cookies on the same domain and they don't have any problem (one is a cookie for the admin login session and the other cookie is to save the user's last viewed articles on the shop)

I tried all solutions found on google without any success : editing php.ini , forcing ini settings through php, tried the htaccess way, ...

Here's the "sessions" part of my phpinfo: http://gyazo.com/168e2144ddd9ee368a05754dfd463021

shop-ajax.php (session handling @ line 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("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $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;

}
?>

There's also 2 other parts of the script : a form to add a sample tshirt to the basket (example.php) and a script to call the ajax (shop-controller.js). Can post it if needed but there's no session handling stuff.

update - Maybe the problem is not related to sessions. The BasketId is lost, but PHPSESSID stays the same in the browser cookies.

I did the following tests for the last 3 days (tested with diferent computers and browsers):

  • Empty browser cookies then start a new session during the afternoon

  • Add 1 item to basket, i write down the BasketId and check the browsers cookies to write down the PHPSESSID

  • Usually always around midnight, the basket empty itself

  • PHPSESSID stays the same in my browser cookies, even after basket empty itself

  • However the BASKETID is not the same, the one used during the afternoon is lost and a new one is regenerated

Server is CentOS 5.9 - PHP Version 5.2.9 (from OVH). Dedicated server on a dedicated IP.

解决方案

First you need to find if the problem is in session's garbage collection or a logical error within the code. For that, you can:

// 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']
    )
);

If this message changes at the same time the basket empties, then you'll know for sure it's a problem with PHP sessions.

In that case, there are a few things you can try:

1) You are doing

$lifetime=60 * 60 * 24 * 365;
$domain = ".mywebsite.com";
session_set_cookie_params($lifetime,"/",$domain);
@session_start();

But according to a user contributed note from PHP.net docs:

PHP's Session Control does not handle session lifetimes correctly when using session_set_cookie_params().

So you may try using setcookie() instead:

$lifetime=60 * 60 * 24 * 365;
session_start();
setcookie(session_name(),session_id(),time()+$lifetime);

Even though it's a 4 year old note as pointed in the comments, I tested it and it still happens (I'm on PHP 5.5.7, Windows Server 2008, IIS/7.5). Only setcookie() produced the HTTP headers to change the expiring date (example setting $lifetime to 600):

Set-Cookie: PHPSESSID=(the id); expires=Mon, 22-Jun-2015 15:03:17 GMT; Max-Age=600

2) If you're using a Debian servers or some derivative, they use a cron job to clear out PHP sessions, so you might try:

3) To find out if there is some process clearing your sessions, you can place a watch on the directory where the session files are stored (actual path varies from server to server, use session_save_path to find out the location on yours). I'm no server admin, but I've read you can use auditctl for that, just make sure you log who made the changes to your files.

4) If you don't have access to server configuration, or don't want to depend on server config (good if you switch hosts), you can implement your own session handler. Check out this example by Pedro Gimeno.

这篇关于php会话随机丢失,无法理解为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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