2010-04-18 80 views
1

您好我创建了两个文件,切换我的论坛(中国语言和英语)有时setcookie()函数不工作

enForum.php

<?php 

    function foo() { 
     global $_COOKIES; 
     setcookie('ForumLangCookie', 'en', time()+3600, '/', '.mysite.com'); 
     echo 'running<br>'; 
     $_COOKIES['ForumLangCookie'] = 'en'; 
     bar(); 
    } // foo() 


    function bar() { 
     global $_COOKIES; 
     if (empty($_COOKIES['ForumLangCookie'])) { 
       die('cookie_name is empty'); 
      } 
      echo 'Language =' . $_COOKIES['ForumLangCookie']; 
      echo "<br>"; 
    } // bar() 

    foo(); 


?> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>forum EN Version</title> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
</head> 

<body> 

please be patient ... 
<script LANGUAGE='javascript'> 

    location.href='http://www.mysite.com/forum/index.php'; 

</script> 


</body> 
</html> 

cnForum.php

<?php 

    function foo() { 
     global $_COOKIES; 
     setcookie('ForumLangCookie', 'cn', time()+3600, '/', '.mysite.com'); 
     echo 'running<br>'; 
     $_COOKIES['ForumLangCookie'] = 'cn'; 
     bar(); 
    } // foo() 


    function bar() { 
     global $_COOKIES; 
     if (empty($_COOKIES['ForumLangCookie'])) { 
       die('cookie_name is empty'); 
      } 
      echo 'Language =' . $_COOKIES['ForumLangCookie']; 
      echo "<br>"; 
    } // bar() 

    foo(); 


?> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>forum CN Version</title> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
</head> 

<body> 

please be patient ... 
<script LANGUAGE='javascript'> 

    location.href='http://www.mysite.com/forum/index.php'; 

</script> 
</body> 
</html> 

有一些文件,包括include template('logon');include template('regist');等,我写了一些c获取Cookie值并控制流以加载不同的模板文件。

$lang = $_COOKIE["ForumLangCookie"]; 
// for Debug 
// echo '$lang is '.$lang; 
// echo '<br/>'; 

if ($lang == "cn"){ 
    include template('logon'); 
} 
else if ($lang == "en"){ 
    include en_template('logon'); 
} 

但有时候SetCookie()不工作。我需要为我的代码添加Sleep(someSeconds);吗?

+0

没有必要使用'$全球_COOKIE' - 这个数组是[几个预定义超全局]之一(http://php.net/manual/ en/language.variables.superglobals.php)并且可以从任何地方访问。 – Crozin 2010-04-18 09:30:33

+0

您可能只包含问题中的一个代码示例,因为它们看起来几乎相同。 – mkj 2010-04-18 09:31:30

+0

@mkj,我想用户点击url链接可以激发不同的语言配置。这就是为什么我创建了两个文件。 – 2010-04-18 09:42:29

回答

1

Cookie可以通过$_COOKIE访问,而不是$_COOKIES

编辑:抱歉误会。我建议您将变量$_COOKIES更改为另一种常见的变量,以便人们可以正确理解您的问题。

+0

@SpanwnCxy,谢谢你的建议。 – 2010-04-19 23:29:40

0

PHP数组名是$ _COOKIE,而不是$ _COOKIES