php session check,How do check if a PHP session is empty?

Is this bad practice?

if ($_SESSION['something'] == '')

{

echo 'the session is empty';

}

Is there a way to check if its empty or it is not set? I'm actualy doing this:

if (($_SESSION['something'] == '') || (!isset($_SESSION['something'])) {

echo 'the session is either empty or doesn\'t exist';

}

Does !isset just checks if a $_SESSION[''] exist and doesn't check if, is there are values in the array or not

karim79

I would use isset and empty:

session_start();

if(isset($_SESSION['blah']) && !empty($_SESSION['blah'])) {

echo 'Set and not empty, and no undefined index error!';

}

array_key_exists is a nice alternative to using isset to check for keys:

session_start();

if(array_key_exists('blah',$_SESSION) && !empty($_SESSION['blah'])) {

echo 'Set and not empty, and no undefined index error!';

}

Make sure you're calling session_start before reading from or writing to the session array.

Use isset, empty or array_key_exists (especially for array keys) before accessing a variable whose existence you are not sure of. So change the order in your second example:

if (!isset($_SESSION['something']) || $_SESSION['something'] == '')

you are looking for PHP’s empty() function

You could use the count() function to see how many entries there are in the $_SESSION array. This is not good practice. You should instead set the id of the user (or something similar) to check wheter the session was initialised or not.

if( !isset($_SESSION['uid']) )

die( "Login required." );

(Assuming you want to check if someone is logged in)

If you want to check whether sessions are available, you probably want to use the session_id() function:

session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).

if(isset($_SESSION))

{}

else

{}

I know this is old, but I ran into an issue where I was running a function after checking if there was a session. It would throw an error everytime I tried loading the page after logging out, still worked just logged an error page. Make sure you use exit(); if you are running into the same problem.

function sessionexists(){

if(!empty($_SESSION)){

return true;

}else{

return false;

}

}

if (!sessionexists()){

redirect("https://www.yoursite.com/");

exit();

}else{call_user_func('check_the_page');

}

The best practice is to check if the array key exists using the built-in array_key_exists function.

来源:https://stackoverflow.com/questions/1519818/how-do-check-if-a-php-session-is-empty

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值