php session偶爾寫入失敗的原因

來源:互聯網
上載者:User

標籤:style   blog   ar   io   color   sp   on   div   art   

session_start();var_dump($_SESSION);$key = sprintf(‘%05d‘, mt_rand(0, 99999));$key = strval($key);$val = time();$_SESSION[$key] = $val;

這是My Code,經測試後大部分情況下無法輸出剛才設定的session,那就是寫入失敗了。

我百思不得其解,如果說失敗的話都要失敗,為何偶爾還有成功的呢?

後來單獨測試的時候把error_reporting 全部開啟了,發現提示這樣的錯誤

 Notice: Unknown: Skipping numeric key 454352 in Unknown on line 0

經查證,為如下原因

The PHP session storage mechanism was originally built around "registering" variables, so the keys in $_SESSION must be names that could be treated as variables in their own right.

This means that $_SESSION[42] is invalid, because $42 wouldn‘t be a valid variable name, and since $foo[42] and $foo[‘42‘] refer to the same thing, $_SESSION[‘42‘] is invalid as well.

The solution is either to use a prefix on your session variables (e.g. $_SESSION[‘row_count_‘ . $x] = $row[‘Count‘];) or make them into an array, which you can then loop over etc later (e.g. $_SESSION[‘row_counts‘] = array(); ... $_SESSION[‘row_counts‘][$x] = $row[‘Count‘];)

Note: this limitation is actually part of the "serialization handler" used when writing the session to disk, which is why the errors have no context (they‘re fired while PHP is shutting down). In very recent versions of PHP there is a setting of session.serialize_handler which doesn‘t have this limitation

php session偶爾寫入失敗的原因

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.