设置Cookie以便下次重定向到相同的点击网址

时间:2015-05-29 19:57:19

标签: php cookies set

我有以下代码

的index.php:

    if(isset($_GET['lang']))
    $translate = new Translator($_GET['lang']);    
    else
    $translate = new Translator('en');

当用户提出这样的请求时

index.php?lang=ru

我希望服务器在下次记住他的请求并将他从index.php重定向到index.php?lang=ru

2 个答案:

答案 0 :(得分:0)

使用:

 if(isset($_GET['lang']))
{
   setcookie("lang", $_GET['lang'], time()+60*60*24*30);
   $lang=$_GET['lang'];
}
elseif (isset($_COOKIE['lang'])) 
{ 
     $lang=$_COOKIE['lang'];
}
else
{
      $lang="en";
}
    $translate = new Translator($lang);

答案 1 :(得分:0)

<?php 
 /*
 *  first get lang from url and set cookie
 */
 if (isset ( $_GET ['lang'] )) {  
    $lang = $_GET ['lang'];
    setcookie ( 'lang', "$lang", time () + 3600 );
} 

/*
 * second if lang is not set in url then read it from cookie
*/
else if (isset ( $_COOKIE ['lang'] )) {  
    header ( "location:redirect.php?lang=" . $_COOKIE ['lang'] );
}

/*
 * if cookie or url is not set then take default lang value 'en'
 */

else {
    $lang = 'en';

    header ( "location:redirect.php?lang=" . $lang );
}

?>