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

标签 php javascript html regex

我正在帮助组建一个网站,该网站将在同一域中托管不同地区的内容。所以例子:

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。 PHP?

系统可以读取他们所在的站点区域以及他们的 cookie 内容。所以我们知道的信息将是:站点:美国和 Cookie:法国。

我正在考虑使用 $_SERVER['SCRIPT_NAME']并使用正则表达式从 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 添加一个检查。它会阻止执行其余代码。

关于PHP:将用户动态转发到不同 URL 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6152095/

相关文章:

javascript - YADCF 插件 - 从 Eonasdan Bootstrap Datetimepicker 获取日期函数

html - 如何强制div的内容显示在移动设备背景图片的下方?

javascript - 单击事件的 jquery 代码不起作用

html - 引导下拉菜单透明按钮

javascript - 根据单选按钮选择显示/隐藏 div

javascript - 使用 JQuery onfocusout 或 onblur 事件时如何重新聚焦于输入元素?

php - php 中的正则表达式- 从字符串中捕获 9 种类型的数字

php - 在 PHP 中创建和使用匿名对象

php - 我想在使用第三个页面时同时链接两个 php 页面

javascript - 如何使用 jquery 库使文本旋转滚动。(需要示例)