Search code examples
phpurl-routing

URL is not working when it's trying it for routing


I'm trying to catch the URL from my localhost, here it is http://localhost/mvc/index.php?url=Index/category and things are going well but when I'm trying to use the URL /category it is showing error. Here is the error

Notice: Array to string conversion in C:\xampp\htdocs\mvc\index.php on line 21

Notice: Undefined property: Index::$Array in C:\xampp\htdocs\mvc\index.php on line 21

Fatal error: Uncaught Error: Function name must be a string in C:\xampp\htdocs\mvc\index.php:30 Stack trace: #0 {main} thrown in C:\xampp\htdocs\mvc\index.php on line 21

<?php
include_once "system/libs/main.php";
include_once "system/libs/Dcontroller.php";
include_once "system/libs/Load.php";
?>
<?php
$url = isset($_GET['url']) ? $_GET['url'] : NULL;
if ($url != NULL) {
    $url = rtrim($url,'/');
    $url = explode("/", filter_var($url,FILTER_SANITIZE_URL));
} else {
    unset($url);
}
if (isset($url[0])){
    include 'app/controllers/'.$url[0].'.php';
    $ctlr = new $url[0]();
    if (isset($url[2])) {
        $ctlr->$url[1]($url[2]);
    } else {
        if (isset($url[1])) {
            $ctlr->$url[1]();  //Here is the line where I'm getting the 
                                 error
        } else {

        }           
    }

}else{
    include 'app/controllers/Index.php';
    $ctlr = new Index();
    $ctlr->home(); 
}   
?>

But when I'm using category() instead of $url[1] it's working fine. Here is the Index class.

<?php
class Index extends Dcontroller
{   
    public function __construct()
    {
        parent::__construct();
    }
    public function home()
    {
        $this->load->view("home");
    }
    public function category()
    {
        $data = array();
        $catModel = $this->load->model("CatModel");
        $data['cat'] = $catModel->catList();
        $this->load->view("category", $data);
    }
}

Solution

  • two things straight away: "/" is not legal in a url param as part of a get string. you need to encapsulate it with URL encodeing

    EG:

      http://localhost/mvc/index.php?url=Index%2Fcategory
    

    it's also the fact that "$ctlr->$url[1]" simply doesn't have a function called it.. eg: whatever "$ctlr->$url[1]" resolves to ??category()?? doesn't exist, you need to MAKE it.

    add this to your code

     function category() {
           Index tmp = new Index();
           tmp->category();
     }
    

    EDIT : I've just noticed, it's even more idiotic than I thought.. your string says Index/category doesn't it?.. make the class method static.. (this code is dreadful by the way it displays almost no sound knowledge of design whatsoever) there is no Index/category because you can't call category inside a class except if it's a static method.

    Learn to code.