开发学院

您的位置:首页>教程>正文

教程正文

CodeIgniter教程:页面重定向

  在构建web应用程序时,我们经常需要将用户从一个页面重定向到另一个页面。CodeIgniter让这项工作对我们来说很容易。重定向()函数用于此目的。

语法

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

参数

  $uri (string) :URI字符串

  $method (string):重定向方式(’auto‘,’location‘或’refresh’)

  $code (string) − HTTP状态码(一般为302或303)

返回类型

void

  第一个参数可以有两种类型的URI,可以是完整的URL或你想要跳转的控制器的URI片段。

  第二个可选参数可以具有’auto‘,’location‘或’refresh’三个值中的任何一个。默认值为auto。

  第三个可选参数仅适用于位置重定向,它允许您发送特定的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://www.kaifaxueyuan.com'); 
      }
      public function computer_graphics() { 
         /*Load the URL helper*/ 
         $this->load->helper('url'); 
         redirect('http://www.tutorialspoint.com/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文件为上述控制器添加路由,在文件末尾添加以下行。

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

  在浏览器中键入以下网址,以执行该示例。

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

  上面的网址将默认把你重定向到kaifaxueyuan.com网站,如果你访问下面的网址,它将把你重定向到tutorialspoint.com的计算机图形教程。

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