【问题标题】:How to get CodeIgniter to ignore the last segment entered into the URL-but still keep it there?如何让 CodeIgniter 忽略输入到 URL 中的最后一段但仍保留在那里?
【发布时间】:2014-01-04 21:54:17
【问题描述】:

我正在使用 CodeIgniter 从头开始​​构建用户配置文件部分。发生的情况是,用户将输入 URL:

www.somesite.com/profile/view/<USERNAME>

profile 是文件夹,view 是控制器)

我将使用 IF ELSE 语句检查 $currentURL(见下文)是否在数据库中并加载所需的页面。

但是现在发生的是它正在寻找一个函数(我认为)在 view 内执行。但是没有。这会导致 404 错误。

CodeIgniter 是否可以忽略该 URL 的最后一段但仍将其保留在那里以便我可以使用;

$currentURL = $this->uri->segment(3);

要获取用户名

感谢您查看我的问题,

刘易斯。

【问题讨论】:

  • CI 只使用你告诉它的东西,通过一个长 URL,你可以选择你想要的 URI 段。你可以制作花哨的 URL,只使用一半的数据而忽略其余的(例如:/view/(postid)/(posttitle)
  • @EHU-Lewis 你得到 404 了吗?

标签: php codeigniter codeigniter-routing


【解决方案1】:

如果我理解正确的话:

如下声明你的函数

public function view($var1, $username = "") {...}

其中$var1必须填写,$username可以省略,默认为""


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class View extends CI_Controller { //can not belive that View is not reserved word

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        //index() function can not have parameters
        //redirect('view/show');
        //if no username is set, do default thing like show list of users
        //load view or something
    }

    public function show($username = "") {
        //this function can have parameters
        //load views from here
        $this->load->view('abc_view');
    }
}

添加到 routes.php 关注

$route['profile/view/(:any)'] = "profile/view/show/$1";

这将允许您拥有您期望的漂亮网址

site.com/profile/view/Peterson123

注意当使用“路由”方法时不要在index()redirect(profile/view/show)


另一种使用_remap() 的方法解释为here

【讨论】:

  • @Jakub 我认为 OP 无法通过 404 错误,这意味着他正在调用没有参数的控制器。这很奇怪,因为 OP 站点结构 www.somesite.com/profile/view/&lt;USERNAME&gt; 我假设 profile 是文件夹,view 是控制器。因此,他缺少视图控制器中的每个“”方法(404 错误)。
  • @Jakub OP 正在寻找 _remap(),因为他说他得到 404。
  • @EHU-Lewis 请注意index() 方法不能有参数,请参阅我的编辑和链接答案。因此,无论您在 index() 中拥有什么,都将其移至新创建的函数 show() 并访问该函数中的所有内容。
  • @EHU-Lewis,每当您通过site.com/profile/view/ 访问您的控制器时,index() 方法(function)都会被首先调用或立即调用,不幸的是index() 不接受任何参数(我们正在谈论 )。所以你需要做的是每当site.com/profile/view被调用时要么将其重定向到site.com/profile/view/show,其中show()函数可以接受参数(如$username,例如site.com/profile/view/show/pete123)或让routes.php处理它。问题是当没有 时,你必须明确地处理它。
  • @EHU-Lewis 然而,我又做了一个编辑!请让自己想想当视图被无参数调用时会发生什么。
猜你喜欢
  • 1970-01-01
  • 2011-09-09
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
  • 1970-01-01
  • 2021-05-21
相关资源
最近更新 更多