CodeIgniter - 页面重定向
在构建 Web 应用程序时,我们经常需要将用户从一个页面重定向到另一个页面。CodeIgniter 使我们可以轻松完成这项工作。redirect() 函数用于此目的。
语法 |
redirect($uri = '', $method = 'auto', $code = NULL) |
参数 |
|
返回类型 |
void |
第一个参数可以有两种类型的 URI。我们可以将完整的站点 URL 或 URI 段传递给您想要定向的控制器。
第二个可选参数可以具有 auto、location 或 refresh 中的任意三个值。默认值为自动。
第三个可选参数仅适用于位置重定向,它允许您发送特定的 HTTP 响应代码。
示例
创建一个名为 Redirect_controller.php 的控制器并将其保存在 application/controller/Redirect_controller.php 中
<?php class Redirect_controller extends CI_Controller { public function index() { /*加载 URL 帮助器*/ $this->load->helper('url'); /*将用户重定向到某个站点*/ redirect('https://www.tutorialspoint.com'); } public function computer_graphics() { /*加载 URL 帮助器*/ $this->load->helper('url'); redirect('https://www.tutorialspoint.com/computer_graphics/index.htm'); } public function version2() { /*加载 URL 帮助器*/ $this->load->helper('url'); /*将用户重定向到某个内部控制器的方法*/ 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