---
title: "nodejs socket.io 结合php 通过 redis来配置登录验证"
author: "李俊良"
date: "2013-11-15T18:33:26Z"
tags: []
categories: ["Web前端"]
slug: "nodejs-socket-io-php-redis"
draft: false
lastmod: "2013-11-15T18:33:26Z"
id: 1975764
url: "https://frosh.iteye.com/blog/1975764"
---

```
io.set('authorization', function (handshakeData, accept) {

    if (handshakeData.headers.cookie) {

        handshakeData.cookie = cookie.parse(handshakeData.headers.cookie);
        if(handshakeData.cookie && handshakeData.cookie['PHPSESSID']){
            
            var sessionClient = redis.createClient();
            var sessionData; 
            sessionClient.get("PHPREDIS_SESSION:"+handshakeData.cookie['PHPSESSID'],function(err,reply){
                console.log("reply:",reply);
                sessionData = reply;
                    //sessionid|i:100;uid|i:100;username|s:4:\"from\";"
                    console.log(sessionData,handshakeData.cookie['PHPSESSID']);
                    if(!sessionData){
                        return accept('not login',false);
                    }
                    console.log(sessionData);
                    var dd = sessionData.split(";");
                    var uid ; 
                    for(var i = 0 ; i < dd.length ; i++){
                        var d = dd[i];
                        var key = d.split("|")[0];
                        if(key == 'uid'){
                        var ser = d.split("|")[1].split(":");
                            uid = ser.length == 2 ? d.split("|")[1].split(":")[1] : ser[2].replace(/[\"\\]/g,"");
                            break;
                        }
                    }
                    console.log("uid",uid);
                    if(uid){
                        handshakeData.uid = uid;
                        return accept(null,true);
                    }else{
                        return accept('userid is empty',false);
                    }
            });
        }else{
            console.log(handshakeData.cookie)
            return accept(null, false);
        }
    }else{
        return accept(null,false);
    }
});
```

   最后返回accept函数

   如果返回accept(null,true)才会进行下面的各种连接

   如果返回false，就不会进行socket连接了

   然后可以在验证的加入一些参数，然后在socket中调用

   socket.handshake.uid

   类似上面设置的uid，在socket中这么调用