LittleStarJenny
LittleStarJenny

Reputation: 17

PHP simple routing - error of undefined offset 0

I'm doing my first php router and tried many tutorials, for example:

The simplest php router, How to build a basic server side...

And a few other, and finally went for this approach Create a PHP routing system

First my problem was that I only got blank pages but after some help from here I got through that problem and now everything works fine except that I'm receiving undefined offset: 0 on my start page.

I'm using array_shift and after that my array is empty:

array(0) { }

So I can see that this is kind of useless to use but the problem is if I remove it or take another approach my router stops working.

Here is my router.php where the problem occurs:

<?php

class Router{

    private $request;

    public function __construct($request){
        $this->request = $request;
    }

    public function get($route, $file){

        $uri = trim( $this->request, "/" );

        $uri = explode("/", $uri);
// var_dump($uri);
         $route = trim($route, "/");
         var_dump($route);
        // if(isset($uri) == $route){
            array_shift($uri);
             var_dump($uri);
            if($uri[0] == $route) {
            //  var_dump($uri);

             require __DIR__ . $file . '.php';
            } 
        // }

    }

}
?>

I tried to wrap the $uri[0] in a if(isset..) statement but that also makes the router stop. I've searched in the php manual for different array functions but to be honest I don't understand what half of it does. Mostly I get most knowledge from searching in this forum and often solves it that way, but this really got me stuck hard.

Anyone who knows how to get rid of this offset error?

Upvotes: 0

Views: 477

Answers (1)

pietrobe03
pietrobe03

Reputation: 51

When calling $route->get($url, $file) you use "/start" and "/product" as files. Inside the get method, you then load "/start".".php" which results in loading "start.php" from the root directory of the hard drive (assuming you use XAMPP on Windows). Replace require $file . '.php'; with require __DIR__ . $file . '.php'; to load the file from your current directory.

Upvotes: 1

Related Questions