on $_GET set $_SESSION wont work

2019-09-17 21:31发布

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?

标签: php session get
3条回答
等我变得足够好
2楼-- · 2019-09-17 22:12

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楼-- · 2019-09-17 22:28

fix this:

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

or you can use:

empty($_SESSION['id_item'])
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-09-17 22:31

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.

查看更多
登录 后发表回答