2014-01-18 18 views
-1

我已經在PHP中創建了一個會話,它創建了一個cookie:PHPSESSID ... 我可以通過使用document.cookie在Chrome中檢測到這個& Opera。然而,在Forefox中,document.cookie也返回由其他域設置的cookie,谷歌分析。如何檢測cookie是否在Javascript中設置?

在PHP中,我設置的會議,如:

session_start(); 
$_SESSION['source'] = &$ref['source']; 
$_SESSION['term'] = &$ref['term']; 
session_write_close(); 

我需要能夠如果這個會話在Javascript中設置,通過定位cookie來檢測。什麼是最好的方式去做這件事?

在我只是用了一下:這好像有點彆彆扭扭的

document.cookie.indexOf('PHPSESSID') 

回答

1

document.cookie屬性將返回所有的餅乾。儘管您的indexOf可以工作,但如果您的Cookie實際數據包含「PHPSESSID」,它將會中斷。它也會匹配以下cookie'MYPHPSESSIDIDIT',因爲它包含您的cookie名稱。

你可以用下面的函數(未測試)解析餅乾:

function getCookieValue(name) 
{ 
    // find cookie entry in middle? 
    var s=document.cookie, 
     c=s.indexOf("; "+name+"="); 

    if(c==-1) 
    { 
     // no, is it at the start? 
     c=s.indexOf(name+"="); 
     if(c!=0) return null; 
    } 

    // get length of value 
    var l=c+name.length+1, 
     e=s.indexOf(";",l); 

    // is it at the end? 
    if(e==-1) e-s.length; 

    // cut out the value 
    return s.substring(l,e); 
} 

希望這有助於

1

使用這個jquery插件,它很酷。

https://github.com/carhartl/jquery-cookie

你可以使用它像這樣:

if($.cookie('PHPSESSID') != undefined){ 
//PHPSESSID exists 
} 
+1

如果將工作太($餅乾( 'PHPSESSID')。)。 –

相關問題