【问题标题】:PHP Header Redirect, If Variable Then RedirectPHP 标头重定向,如果变量则重定向
【发布时间】:2019-03-09 19:40:28
【问题描述】:

我想使用一个 URL 将用户重定向到各种传出 URL。例如http://example.com/out.php?ofr=2,其中ofr 将指代用户应重定向到的相应 URL。

我有以下out.php的php代码

这是可以接受的,还是有更有效的方法来完成这个(假设下面的脚本中有 10 个左右不同的 URL)?

<?php

$ofr = $_GET['ofr'];

if ($ofr == 1) {
    header('location: http://google.com');
}
elseif ($ofr == 2) {
    header('location: http://yahoo.com');
}
else {
    header('location: http://msn.com');
}

?>

编辑:按照建议查看 switch 语句,我相信它看起来像:

$ofr = $_GET['ofr'];

switch ($ofr){
case 1: header('location: http://example_1.com');
break;
case 2: header('location: http://example_2.com');
break;
default: header('location: http://example_2.com');
break;
}

看起来正确吗?谢谢!

【问题讨论】:

  • 好吧,您可以将位置打包到一个数组中,因此您只需检查一次密钥是否存在,而不是编写大量的if-statements。 (顺便说一句:switch-statements 确实存在)
  • @FranzGleichmann 我编辑了我认为 switch 语句的样子。感谢您的提示。

标签: php


【解决方案1】:

首先我建议像这样做一个重定向功能:

function redirect($url)
{
    $baseUri=_URL_;

    if(headers_sent())
    {
        $string = '<script type="text/javascript">';
        $string .= 'window.location = "' . $baseUri.$url . '"';
        $string .= '</script>';

        echo $string;
    }
    else
    {
    if (isset($_SERVER['HTTP_REFERER']) AND ($url == $_SERVER['HTTP_REFERER']))
        header('Location: '.$_SERVER['HTTP_REFERER']);
    else
        header('Location: '.$baseUri.$url);

    }
    exit;
}

然后在一个名为redirectFiles.php 的文件中创建要重定向的url 数组:

$redirecUrls = [
  'location: http://example_1.com',
  'location: http://example_2.com',
  'location: http://example_3.com',
]

然后做一个函数来做重定向:

function redirectUrls($index){
   if(isset($redirecUrls[ $index])
      return redirect($redirecUrls[ $index])

   return false;
}

之后你可以这样做:

$ofr = $_GET['ofr'];
if($ofr!='')
  redirectUrls($ofr)

【讨论】:

  • 谢谢。这会比使用我在原帖中添加的切换方法更有效吗?
  • @rivitzs 是的。这都是关于干净的代码。这样你就可以制作一个(类似路由的)系统。总是尝试在单独和可重用的功能中做事。始终考虑可能会出现问题,您的代码会崩溃。如果你把你的代码分开,调试过程会更容易。
  • @rivitzs 如果您不检查之前发送的标头可能会引发致命错误,即标头之前已发送并且您不能使用 header('location 任何你喜欢的地方。但使用我的重定向功能,它无论如何总是重定向。您可以删除基本 URL 变量以满足您的需要
  • 很好,有道理。谢谢你的解释。
【解决方案2】:

试试这样的:

 <?php
 $ofr=$_GET['ofr'];
 $url_array=array([1]=>http://google.com [2]=>http://yahoo.com);
 foreach($url_array as $key=>$value)
 {  
   if($ofr==$key)  
   header('location: ".$value."');
 }
?>

【讨论】:

  • 我明白你在说什么。我在示例代码中有点误导,因为重定向会转到不同的站点。 ofr=1 可以访问 google.com,ofr=2 可以访问 yahoo.com。那是我的错......我会更新原来的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 2012-12-16
  • 2011-04-15
相关资源
最近更新 更多