【问题标题】:Make dynamic redirection php based on parameters sent根据发送的参数进行动态重定向php
【发布时间】:2016-11-04 04:44:11
【问题描述】:

假设我有一个参数化的 url,可以重定向到其他 url。

示例:

http://XxxXX.net/redirect.php?param1={param1}&param2={param2}&param3={param3}&param4={param4}

我在redirect.php中有以下内容

<html><head>
     <script>
     function getURLParameter(name) {
         return decodeURI(
                (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1] || ''
            );
        }
</script>

    <script>
    var param1 = getURLParameter('param1'); 
    var param2 = getURLParameter('param2'); 
    var param3 = getURLParameter('param3'); 
    var param4 = getURLParameter('param4'); 

    var url = 'http://xxxx.xxxxx.net/yyyy/'+param1+'?param2='+param2+'&param3='+param3+'&param4='+param4';

  </script>
</head>
<?php    
header('Location: url');    
?>
<body>

</body></html>

现在,想法是来自第一个调用 redirect.php 的 url 的参数可以满足我希望 recirect.php 执行的操作。

然后根据收到的参数重定向到动态 url。

这可能吗?

也许我的代码有问题,请帮助我。

【问题讨论】:

    标签: php redirect parameter-passing url-redirection url-parameters


    【解决方案1】:

    即使这个问题有一个公认的答案,我仍然提供以下解决方案,因为:

    1. 问题被标记为 PHP,而不是 JavaScript
    2. 接受的答案不是最初要求的动态解决方案

    然后根据收到的参数重定向到一个动态的url。

    示例网址:http://localhost/test.php?hello=world&amp;foo=bar

    获取查询字符串参数:

    $query = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
    parse_str($query, $result);
    
    echo '<pre>';
    print_r($result);
    echo '</pre>';
    

    输出:

    Array
    (
        [hello] => world
        [foo] => bar
    )
    

    执行重定向:

    header('Location: http://www.example.com/?' . http_build_query($result));
    

    这将重定向到:http://www.example.com/?hello=world&amp;foo=bar

    【讨论】:

    • 我可以看到您的解决方案正在运行,您是对的,这是 PHP。但是第一个是动态的,它根据最初发送的参数创建了“url”参数。还是我看错了什么?如果我发送 url.com/?paramX=yyy 它将重定向到 example.com/?paramx=yyy 这是我需要的..
    • @gasguirre 在您的原始问题中,您正在根据参数手动定义四个变量,param1、param2、param3 和 param4。如果您每次都必须手动创建它们,则它不是动态的。我的代码可以使用一个参数或 50 个参数,您不需要事先知道有多少。
    • 可能想查看parse_str() 而不是循环播放。
    • @AbraCadaver 感谢您的提示,更新了我的示例。
    • 我现在明白了,好吧,就我而言,我知道要传递多少个参数,来自它们的数据会有所不同。但现在我明白了。谢谢。您的解决方案确实是这里最好的。
    【解决方案2】:

    您需要在 PHP 中进行重定向吗?

    如果没有,您可以使用window.location = url; 或window.location.replace(url);

    【讨论】:

    • 它是 JavaScript,所以如果你不是特别需要在 PHP 中进行重定向,你可以这样做。
    • 嗯,实际上是这样,对吧?因为它调用动态填充的 URL。所以它有效,还是我错过了什么?
    • 您说“根据接收的参数重定向到动态 url”...这不是动态的,因为您必须事先知道发送了多少参数。@gasguirre
    猜你喜欢
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多