CodeIgniter - 頁面重定向



在構建 Web 應用程式時,我們經常需要將使用者從一個頁面重定向到另一個頁面。CodeIgniter 使這項工作變得簡單。redirect() 函式用於此目的。

語法

redirect($uri = '', $method = 'auto', $code = NULL)

引數

  • $uri (字串) - URI 字串

  • $method (字串) - 重定向方法('auto'、'location' 或 'refresh')

  • $code (字串) - HTTP 響應程式碼(通常為 302 或 303)

返回型別

void

第一個引數可以包含兩種型別的 URI。我們可以將完整的站點 URL 或 URI 段傳遞到您要重定向到的控制器。

第二個可選引數可以具有 auto、location 或 refresh 中的任意三個值。預設值為 auto。

第三個可選引數僅在 location 重定向中可用,它允許您傳送特定的 HTTP 響應程式碼。

示例

建立一個名為 Redirect_controller.php 的控制器,並將其儲存在 application/controller/Redirect_controller.php 中。

<?php 
   class Redirect_controller extends CI_Controller { 
	
      public function index() { 
         /*Load the URL helper*/ 
         $this->load->helper('url'); 
   
         /*Redirect the user to some site*/ 
         redirect('https://tutorialspoint.tw'); 
      }
		
      public function computer_graphics() { 
         /*Load the URL helper*/ 
         $this->load->helper('url'); 
         redirect('https://tutorialspoint.tw/computer_graphics/index.htm'); 
      } 
  
      public function version2() { 
         /*Load the URL helper*/ 
         $this->load->helper('url'); 
   
         /*Redirect the user to some internal controller’s method*/ 
         redirect('redirect/computer_graphics'); 
      } 
		
   } 
?>

更改 application/config/routes.php 中的 routes.php 檔案以新增上述控制器的路由,並在檔案末尾新增以下行。

$route['redirect'] = 'Redirect_controller'; 
$route['redirect/version2'] = 'Redirect_controller/version2'; 
$route['redirect/computer_graphics'] = 'Redirect_controller/computer_graphics';

在瀏覽器中鍵入以下 URL 以執行示例。

http://yoursite.com/index.php/redirect

以上 URL 將重定向您到 tutorialspoint.com 網站,如果您訪問以下 URL,則它將重定向您到 tutorialspoint.com 上的計算機圖形教程。

http://yoursite.com/index.php/redirect/computer_graphics
廣告