John
John

Reputation: 3050

Manipulate URL $_SERVER['REQUEST_URI']

This is my url: http://localhost/framework/index.php

echo $_SERVER['REQUEST_URI'];

Would output: /framework/index.php

But If my url was:

http://localhost/framework/

The output would be:

/framework/

And If I move the file, yeah you get the idea.

How do I grab the content after folders/eventually index.php file? My idea is to have index.php as a front controller.

If I have:

http://localhost/framework/index.php/test/test

I only want the test/test part.

http://localhost/framework/test/test

I only want the test/test part.

Upvotes: 1

Views: 8180

Answers (1)

Daveo
Daveo

Reputation: 1225

You can automatically detect the base uri and remove it, leaving you with the test/test part.

if(!empty($_SERVER['PATH_INFO']))
{
    // Uri info does not contain docroot or index
    $uri = $_SERVER['PATH_INFO'];
}
else
{
    if(!empty($_SERVER['REQUEST_URI']) && !empty($_SERVER['HTTP_HOST']))
    {
       $fullUrl = 'http://'
                  . ((isset($_SERVER['HTTP_HOST'])) ? $_SERVER['HTTP_HOST'] : '')
                  . ((isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : '');

       $uri = parse_url($fullUrl, PHP_URL_PATH);
    }
    else if(!empty($_SERVER['PHP_SELF']))
    {
       $uri = $_SERVER['PHP_SELF'];
    }
}

$baseUri = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], "/")+1);
$uri = str_replace($baseUri, '', $uri);

Edit: mAu's comment above is correct. I was under the assumption you was already using mod rewrite.

Upvotes: 6

Related Questions