PHP从cookie中获取多个值

时间:2017-03-09 04:12:18

标签: php

我正在使用asp.net页面(VB)存储多个值的cookie。然后我尝试从PHP中检索cookie中的值,并且找不到使用PHP获取多个值的方法

$myRole仅返回" R"不是"管理员"

php full cookie var_dump($myCookie);string(48) "Role=admin&User=myuser&Time=3/8/2017 8:08:43 PM"

ASP.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim sb As New StringBuilder()
     Dim cookie As HttpCookie
    cookie = Request.Cookies.Get("PHPAUTH")

    If (cookie Is Nothing) Then
        sb.Append("Cookie was not received from the client. ")
        sb.Append("Creating cookie to add to the response. <br/>")
        cookie = New HttpCookie("PHPAUTH")


        If Not Roles.IsUserInRole(User.Identity.Name, "admin") Then
            'cookie.Values("Role") = "not in role"
        Else
            cookie.Values("Role") = "admin"
            cookie.Values("User") = User.Identity.Name
        End If 

        cookie.Values("Time") = DateTime.Now.ToString()
        cookie.Expires = DateTime.Now.AddMinutes(10D)
        Response.Cookies.Add(cookie)
    Else
        sb.Append("Cookie retrieved from client. <br/>")
        sb.Append("Cookie Name: " + cookie.Name + "<br/>")
        sb.Append("Cookie User: " + cookie.Values("User") + "<br/>")
        sb.Append("Cookie Role: " + cookie.Values("Role") + "<br/>")
        sb.Append("Cookie Time: " + cookie.Values("Time") + "<br/>")
        sb.Append("Cookie Expiration Date: " & _
            cookie.Expires.ToString() & "<br/>")
    End If

    Label1.Text = sb.ToString()

End Sub

PHP:

$myCookie = $_COOKIE["PHPAUTH"];
$myRole = $myCookie["Role"];
var_dump($myCookie);
var_dump($myRole);

1 个答案:

答案 0 :(得分:0)

似乎需要将cookie字符串解析为数组:

PHP Set and Read a Cookie String

我的解决方案是:

$myCookie = $_COOKIE["PHPAUTH"];
parse_str($myCookie, $prefs);
var_dump($prefs);
echo print_r($prefs['Role']);