doupang5433 2015-04-02 18:14
浏览 29

全局变量如何在php中工作?

I am a php newbie and am going through the code of retwis as redis tutorial. While going through the code, I ran into following piece of snippet

function isLoggedIn() {
global $User, $_COOKIE;

if (isset($User)) return true;

if (isset($_COOKIE['auth'])) {
    $r = redisLink();
    $authcookie = $_COOKIE['auth'];
    if ($userid = $r->hget("auths",$authcookie)) {
        if ($r->hget("user:$userid","auth") != $authcookie) return false;
        loadUserInfo($userid);
        return true;
    }
}
return false;}

function loadUserInfo($userid) {
global $User;

$r = redisLink();
$User['id'] = $userid;
$User['username'] = $r->hget("user:$userid","username");
return true;}

So what the code is doing here is that, when a user opens say index.php, we call isLoggedIn, if the user satisfied the authentication then we load the user info (id and username) in the global $User variable and use it other php pages to display information much like session variables.

My question how is this use of global variable correct? Are not global variable shared across the application(for multiples users)? If lets say user1 logs in and we set $User with user1 credential and then user2 logs in, wont then the $User variable be changed/overriden with data of user2 and show incorrect data for user1? But in application everything is working fine, Can anyone explain to me what I am doing wrong?

  • 写回答

1条回答 默认 最新

  • dtc88867 2015-04-02 18:20
    关注

    PHP doesn't have any application-level persistence. Use APC or memcache to store such values. You can not only access these values from any page but can also access from any server and in a faster way.

    but won't this User global variable be shared between multiple users which might cause conflicts? Does each user have its on copy? @Dude

    It depends. This will be up to you. Memcache (btw I recommended you memcached) it is "like" a table with keys and values

    +-------+--------+
    |  Key  | Value  |
    +-------+--------+
    | User1 | Value1 |
    | User2 | Value2 |
    | User3 | Value3 |
    +-------+--------+
    

    You can code so each key can be user ID and the value can be an object, serialized object or whatever. In this case you don't have any conflict. However, if you want,you can share the same resource (use the same key for everyone), but I don't think that is what you want)

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题