有没有更好的方法来处理cookie /重定向

时间:2012-01-03 16:51:04

标签: php cookies mobile redirect

我已为我们整理了一个移动网站,如果设备是移动设备,请将主网站madisonstudios.com重定向到移动网站madisonstudios.mobi。

我还在移动网站上放置了一个完整的网站按钮,当推荐者是移动网站时,它设置了一个cookie,但我仍然有问题,仍然让它在第一次点击时重定向到整个网站,然后一旦你第二次点击它就进入完整的网站。

要解决此问题,我添加了$setcookie变量并将其设置为1,以便跳过重定向。我的代码如下。

我认为这是一种混乱的方式,并且认为必须有一种更清洁的方式,是否有人有一个对我来说有意义的建议。我是以正确的方式来做这件事吗?

<?php
if($_SERVER['HTTP_REFERER'] == "http://www.madisonstudios.mobi/" || $_SERVER['HTTP_REFERER'] == "http://madisonstudios.mobi/")
{
    setcookie('fromMobi', true, time()+3600*24);
    $setcookie = 1;
}

if ($_COOKIE["fromMobi"] == 1 || $setcookie == 1)
{

} else {
    $uamatches = array("midp", "j2me", "avantg", "docomo", "novarra", "palmos", "palmsource", "240x320", "opwv", "chtml", "pda", "windows\ ce", "mmp\/", "blackberry", "mib\/", "symbian", "wireless", "nokia", "hand", "mobi", "phone", "cdm", "up\.b", "audio", "SIE\-", "SEC\-", "samsung", "HTC", "mot\-", "mitsu", "sagem", "sony", "alcatel", "lg", "erics", "vx", "NEC", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch", "rover", "pocket", "benq", "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda", "sany", "kdd", "dbt", "sendo", "sgh", "gradi", "jb", "\d\d\di", "moto","webos");

    foreach($uamatches as $uastring){
    if(preg_match("/".$uastring."/i",$_SERVER["HTTP_USER_AGENT"]))
    {
    header('Location: http://www.madisonstudios.mobi');
    }
    }
}
?>

1 个答案:

答案 0 :(得分:2)

我会这样做:

<?php

  // Use stripos() for tidiness, case-insensitivity and ignoring subdomains and paths
  if (stripos($_SERVER['HTTP_REFERER'],'madisonstudios.mobi') !== FALSE) {

    // We came from mobi, set the cookie that says so
    setcookie('fromMobi', true, time()+3600*24);

  } else if (empty($_COOKIE["fromMobi"])) {
    // We only do this if the cookie is not set or it has a value that evaluates
    // to FALSE - empty() does this check for us in one go

    // Look for mobile browsers and redirect them to mobi
    $uamatches = array("midp", "j2me", "avantg", "docomo", "novarra", "palmos", "palmsource", "240x320", "opwv", "chtml", "pda", "windows\ ce", "mmp\/", "blackberry", "mib\/", "symbian", "wireless", "nokia", "hand", "mobi", "phone", "cdm", "up\.b", "audio", "SIE\-", "SEC\-", "samsung", "HTC", "mot\-", "mitsu", "sagem", "sony", "alcatel", "lg", "erics", "vx", "NEC", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch", "rover", "pocket", "benq", "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda", "sany", "kdd", "dbt", "sendo", "sgh", "gradi", "jb", "\d\d\di", "moto","webos");
    foreach ($uamatches as $uastring) {
      if (preg_match("/".$uastring."/i",$_SERVER["HTTP_USER_AGENT"])) {
        header('Location: http://www.madisonstudios.mobi/');
        // If we find one we know we can exit straight away because the user
        // is getting redirected
        exit;
      }
    }

  }