Dach0
Dach0

Reputation: 337

Understanding $_SERVER[REQUEST_URI]

I'm following LARACAST PHP practitioner classes and I had a problem with $_SERVER[REQUEST_URI].

It always returns 404 not found if I write in browser for url: localhost/laracast/about and I have in router->define just 'laracast' => 'controllers/index.php' , or some other page after laracast/ except index. I had to change it to localhost/laracast/index.php/about to make it work, and every other page. I've lost all day figuring out this and I still don't understand why it simply doesn't throw an exception I've declared in class if I omit index.php in my routes rather than 404 error. Does it have something with server or what?

The code is next:

routes.php

$router->define([

'laracast/index.php' => 'controllers/index.php',
'laracast/index.php/about' => 'controllers/about.php',
'laracast/index.php/about/culture' => 'controllers/about-culture.php',
'laracast/index.php/contact' => 'controllers/contact.php']);

Router class

class Router
{

    private $routes = [];

    public function define($routes){
        $this->routes = $routes;
    }

    public static function load($file){

        $router = new static;
        require $file;
        return $router;
    }


    public function direct($uri)

    {

        if(array_key_exists($uri, $this->routes)){

            return $this->routes[$uri];
        }

        throw new Exception("No route defined for this URI");

    }

}

and index.php

<?php 

$query = require 'core/bootstrap.php';

$uri = trim($_SERVER['REQUEST_URI'], '/');

require Router::load('routes.php')

        ->direct($uri);

With this url http://localhost/laracast/index.php/about it works just fine, and all the other pages preceded by index.php. Any explanation and/or suggestions, or this is a valid solution?

Upvotes: 0

Views: 1302

Answers (1)

Dach0
Dach0

Reputation: 337

Thanks to @Martin Zeitler instructions and doing some research I've make it work. In .htaccess file I've just added this peace of code.

<IfModule mod_rewrite.c>
    RewriteEngine On
    Options +FollowSymLinks -Indexes

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

and now it recognizes routes.

Upvotes: 2

Related Questions