on $_GET set $_SESSION wont work

僤鯓⒐⒋嵵緔 提交于 2019-12-12 04:55:24

问题


I need to get the last non-empty value that $_GET['id_item'] had

session_start();

if(!isset($_SESSION['id_item']) || $_SESSION['id_item']===''  || ( isset($_GET['id_item']) && !$_GET['id_item'] === '' )){
    $_SESSION['id_item'] = $_GET['id_item'];
}else{
   /*no need to update*/
}

echo $_SESSION['id_item']   /*   Allways in blank    :S   */

And var_dump($_GET) outputs:

array(1) { ["id_item"]=> string(2) "50" } 

Any idea why the $_SESSION is not saved?


回答1:


fix this:

$_SESSION['id_item']=='' to $_SESSION['id_item']===''

or you can use:

empty($_SESSION['id_item'])



回答2:


unless you expect a (valid) ID to be 0 you can reduce !isset($_SESSION['id_item']) || $_SESSION['id_item']==='' to empty($_SESSION['id_item']). !$_GET['id_item'] === '' is always false, as this translates to false === ''. You were probably looking for $_GET['id_item'] !== ''. Again, if 0 is not a valid value, you can go for !empty($_GET['id_item']) here.

That said, the whole !isset($_SESSION['id_item']) || $_SESSION['id_item']==='' part of the condition doesn't make much sense. The second part "if _GET id_item present" is always necessary for the condition's body ($_SESSION['id_item'] = $_GET['id_item'];) to work. So you can reduce your condition to

<?php
if (!empty($_GET['id_item'])) {
    // import new id_item
    $_SESSION['id_item'] = $_GET['id_item'];
} elseif (!isset($_SESSION['id_item'])) {
    // make sure we don't run into an undefined array index notice
    $_SESSION['id_item'] = null;
}

var_dump($_SESSION['id_item]);



回答3:


Have you output anything before the start_session. If so it will be unable to send the cookie. This is probably why it is not working.



来源:https://stackoverflow.com/questions/9453067/on-get-set-session-wont-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!