繁体   English   中英

PHP标头重定向,如果变量则重定向

[英]PHP Header Redirect, If Variable Then Redirect

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

我有以下php代码用于out.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;
}

看起来正确吗? 谢谢!

首先,我建议制作一个重定向函数,如下所示:

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的文件中,制作要重定向的网址的数组:

$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)

尝试这样的事情:

 <?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."');
 }
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM