如何使用两个参数在Codeigniter中验证路由URL?

时间:2018-08-18 18:19:30

标签: php codeigniter

我对Codeigniter 3有问题

在我的文件route.php中

$route['article/(:num)/(:any)'] = 'article/index/$1/$2';

在我的文件article.php中

<?php

defined('BASEPATH')或exit('不允许直接脚本访问');

类文章扩展了Frontend_Controller {

public function __construct()
{
    parent::__construct();
    $this->data['recent_news'] = $this->article_m->get_recent();
}

public function index($id, $slug)
{
    // Fetch the article
    $this->article_m->set_published();
    $this->data['article'] = $this->article_m->get($id);

    // Return 404 if not found uri_string() return blog/comments/123
    count($this->data['article']) || show_404(uri_string());

    // Redirect if slug was incorrect
    $request_slug = $this->uri->segment(3);
    $set_slug = $this->data['article']->slug;
    if ($request_slug != $set_slug) {
        // with 301 redirect
        redirect('article/' . $this->data['article']->id . '/' . $this->data['article']->slug, 'location', 301);
    }
    // Load view
    add_meta_title($this->data['article']->title);
    $this->data['subview'] = 'article';
    $this->load->view('_main_layout', $this->data);
}

}

当我输入网址http://ci-cms.com/article/6/confesion时 可以,但是如果我输入网址http://ci-cms.com/article 我有这样一个问题:

An uncaught Exception was encountered

类型:ArgumentCountError

消息:函数Article :: index()的参数太少,第532行的C:\ xampp \ htdocs \ ci-cms \ system \ core \ CodeIgniter.php中传递了0,并且正好是2个

文件名:C:\ xampp \ htdocs \ ci-cms \ application \ controllers \ article.php

行号:12

回溯:

文件:C:\ xampp \ htdocs \ ci-cms \ index.php 线:320 功能:require_once

如何解决此问题?,请帮助我,我是这个框架的新手...

谢谢。

1 个答案:

答案 0 :(得分:0)

您期望发生什么?转到http://ci-cms.com/article应该转到索引方法。该错误表明您缺少$ id和$ slug参数。

您可以执行以下操作:

public function index($id = NULL, $slug = NULL)
{ 

但是您随后需要添加代码来检查以确保$ id和$ slug不为空。

赞:

public function index($id = NULL, $slug = NULL)
{
    if (!is_null($id) && !is_null($slug))
    {
        // Fetch the article
        $this->article_m->set_published();
        $this->data['article'] = $this->article_m->get($id);

        // Return 404 if not found uri_string() return blog/comments/123
        count($this->data['article']) || show_404(uri_string());

        // Redirect if slug was incorrect
        $request_slug = $this->uri->segment(3);
        $set_slug = $this->data['article']->slug;
        if ($request_slug != $set_slug)
        {
            // with 301 redirect
            redirect('article/' . $this->data['article']->id . '/' . $this->data['article']->slug, 'location', 301);
        }
        // Load view
        add_meta_title($this->data['article']->title);
        $this->data['subview'] = 'article';
        $this->load->view('_main_layout', $this->data);
    }
}