PHP:将用户动态转发到不同URL的最佳方式

PHP: Best way to forward a user to a different URL dynamically

本文关键字:URL 最佳 方式 用户 动态 转发 PHP      更新时间:2023-09-26

我正在帮助建立一个网站,该网站将托管同一域上不同地区的内容。例如:

www.example.com/us/
www.example.com/uk/
www.example.com/fr/

我有一个系统,询问用户他们想查看哪个网站(然后将他们的偏好存储在cookie中)。我的问题是:如果他们访问了一个URL(例如:www.example.com/us/contact.php),并且他们的首选cookie显示/fr/,我如何最好地将他们转发到www.example.com/fr/contact.hp?

该系统可以读取他们所在的网站区域以及他们的cookie显示的内容。所以我们知道的信息是:网站:美国和Cookie:FR.

我想使用$_SERVER['SCRIPT_NAME']并使用regex从URL中获取"contact.php"。然后使用header("Location: [url]");,但我知道如果任何文本已经传递到浏览器,Location就不起作用。。。这就产生了各种各样的问题。

编辑:
这里有一些代码可以更清楚地解释这个问题:

<?php
// Get variable contents for $cookieRegion and $siteRegion
if($cookieRegion != '') { // If Cookie has been previous set
    if($cookieRegion != $siteRegion) { // If Cookie pref clashes with site URL
       // Forward to correct URL
    }
}
else { ?>
    <script type="text/javascript">
        $(document).ready(function(){
            // Display modal window asking user preference
        });
    </script>        
<?php } ?>

因此<script>标签将被放置在文档开始之前。。。不是个好主意!

解决这个问题的最佳方法是什么?

或者,有没有一种更好的方法来处理整个问题,我可以实现它?

<?php
// Use this to open modal window.
$wrongRegion = FALSE;
// if there is a cookie...
if (isset($_COOKIE['region']))
{
    // I am using preg_match to ensure we are getting right parameters...
    // Sorry I am not good with Regex. You can set a better patern.
    preg_match("#/(.*?)/(.*?)'.php#is", $_SERVER['REQUEST_URI'], $m);
    // Okay! $m[1][0] is the region code on the uri. lets check if its same with cookie
    if ($_COOKIE['region'] != $m[1][0])
        $wrongRegion = TRUE;
}
....... (codes goes here)
// to where you put the modal window code:
if ($wrongRegion == TRUE)
{
    // put the modal window code.
}

这样您就可以在preg_match中添加一个复选框。它阻止执行其余的代码。

将以下代码或一些等效代码放在ANY HTML或换行符之前。

<?php
# This will split the request URI into an array with all the components between slashes in the URI
$request_parameters = explode('/', $_SERVER['SCRIPT_URI']);
# Now, hopefully $request_parameters[1] contains the language abbreviation/code
if ( $request_parameters[1] != $cookieLanguage ) {
    # Replace the erroneous language with the language saved in the cookie, 
    # reassemble the URI and send the client to the correct location
    $request_parameters[1] = $cookieLanguage;
    header('Location: ' . implode('/', $request_parameters);
}

如果没有任何cookie集

  1. 显示默认页面,例如/en-US/contact/
  2. 让客户选择语言
    • 如果客户选择了一种语言;设置语言cookie并重新加载页面

首先读取cookie,然后解析用户想要去的地方(contact.php),然后在发送输出之前用Location:重定向它,所以在index.php的开头

这实际上非常简单。

在脚本的开头(在任何html之前,尤其是标签!)按照以下几行做一些事情:

 <?
 if $locationCookie == 'fr') {
 header("Location: /fr");
 //or alternatively
 //header("Location: /fr/contact.php");
 }
 //also, let's say they are on the us/contact.php page and you want them to go to the fr/contact.php page
 header('Location: ../'.$language_cookie.'/contact.php');
 ?>

这样做的目的是将用户重定向到他们当前所在的同一页面,但语言的$_GET变量将等于fr。然后,在您的页面中,您应该检查该变量并相应地进行适当的更改。