代码之家  ›  专栏  ›  技术社区  ›  adam

Silverstripe在主页上检测语言和重定向

  •  0
  • adam  · 技术社区  · 6 年前

    在我使用silverstripe 3的客户网站上,我正试图建立一个基于用户语言的主页重定向。

    这是我第一次使用这个cms,所以我在 mysite\code\pages 文件夹文件名为 StartPage.php 使用以下代码

    class StartPage_Controller extends Page_Controller {
    
       public function init() {
          parent::init();
    
          $ip = $_SERVER['REMOTE_ADDR'];
          $data = json_decode(file_get_contents('http://freegeoip.net/json/' . $ip));
    
          if ($data->country_code == 'PL') {
             $this->redirect('pl/start', 301);
          } else {
             $this->redirect('en/home', 301);
          }
        }
       }
    }
    

    这没有产生任何结果,该站点仍然重定向到 /en/home ,因此,我试图在任何情况下通过只离开来强制重定向 $this->redirect('pl/start', 301); 仍然没有结果。

    因此,通过进一步涉猎,我编辑了 _config.php 文件,并在顶部添加了这些行

    $currentpage = $_SERVER['REQUEST_URI'];
    
    if ($currentpage == '/' or $currentpage =='') {
    
      $lc = ""; // Initialize the language code variable
      if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
          $lc = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
      }
      if($lc == "pl"){
          header("location: /pl");
          exit();
      }
      if ($lc == 'de') {
          header("location: /de");
        exit(  );
      }
      else{
          header("location: /en");
      }  
    }
    

    这有点好,例如在chrome桌面上,语言被正确重定向,但在移动chrome和Firefox上,它仍然被重定向到英语页面。

    0 回复  |  直到 6 年前
    推荐文章