簡體   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