MateuszC
MateuszC

Reputation: 499

Reading URL in PHP/HTACCESS

I want to create a system that reads a URL provided by the user and then slices it to an array, so it can output different pages from the outcome.

Let me create a sample pseudocode for this

//Url in borwser is http://example.com/user/frank
//this is index.php file in examplepage.com
//folders user and user/frank do not exist

$url = read_url();
//$url[0] = 'example.com';
//$url[1] = 'user';
//$url[2] = 'frank';

if($url[1]=='user' && $url[2]=='frank'){
    include_frank_page():
}else if($url[1]=='user' && $url[2]=='john'){
    include_john_page():
}else{
    include_user_error_page():
}

How can I do such a thing? I know WordPress does something like this, but I can't find a part of the code that does that. Does this have something to do with .htacces file it creates?

If you will provide me any link to any description or tutorial, I will be very thankful.

EDIT: Ok, FallbackResource /index.php is exactly what I need, but there is a 502 Proxy Error.

I have .htacces that looks like this:

FallbackResource /test/index.php

And index.php in test

echo $_SERVER['REQUEST_URI'];

Both of those are in 'test' folder in my example.com root directory. I want to do this only in this folder for obvious reasons.

When I type example.com/test/aaa result is '/test/aaa' - ok.

When I type example.com/test/aaa/bbb result is '/test/aaa/bbb' - ok.

When I type example.com/test/ there is "502 proxy error". How can I avoid that?

EDIT 2: Also, when I created folder test2 inside my test folder, and typed example.com/test/test2 - there was also 502 proxy error.

Upvotes: 1

Views: 222

Answers (1)

MrWhite
MrWhite

Reputation: 45968

You could implement a "front controller" in .htaccess that routes all requests to a single file, eg. index.php. (This is what WordPress does).

Then, in index.php you examine the URL and load the appropriate content.

For example, in .htaccess:

FallbackResource /index.php

This routes all requests for non-existent files through index.php in the document root. (WordPress uses a mod_rewrite implementation.)

Then, in index.php you can do something like:

// Actual HTML pages stored in a (hidden) subdirectory called "/pages"
$pageDir = $_SERVER['DOCUMENT_ROOT'].'/pages';
$pages = array (
    '/home' => 'home.php',
    '/about' => 'about.php',
    '/contact => 'contact.php',
);

// $_SERVER['REQUEST_URI'] contains the URL of the request
$url = $_SERVER['REQUEST_URI'];
if (isset($pages[$url])) {
    include($pageDir.'/'.$pages[$url]);
} else {
    // NB: The "error-404.php" page will need to return the appropriate HTTP status
    include($pageDir.'/error-404.php');
}

Upvotes: 1

Related Questions