繁体   English   中英

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

[英]How to validate routing url in codeigniter with two parameters?

我的Codeigniter 3有问题

在我的文件route.php中

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

在我的文件article.php中

<?php

define('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);
}

}

当我输入的URL http://ci-cms.com/article/6/confesion这是确定的,但如果我输入的URL http://ci-cms.com/article我有一个问题,因为这样的:

An uncaught Exception was encountered

类型:ArgumentCountError

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

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

行号:12

回溯:

文件:C:\\ xampp \\ htdocs \\ ci-cms \\ index.php行:320函数:require_once

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

谢谢。

您期望发生什么事? 转到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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM