Mitch Evans
Mitch Evans

Reputation: 641

Get information from URL

How could I get the information after my main url with php?

Like let's say I have a url like this:

http://www.myawesomedomain.com/about

How could I pull the about part of that url out and use it in php?

I know you can use the $_GET[] variable for url but I don't want to mess up the url. What is a quick and easy way to do this?

Upvotes: 1

Views: 366

Answers (5)

Rob
Rob

Reputation: 224

  • step 1) get the REQUEST URI from the _SERVER["REQUEST_URI"]; $url = _SERVER["REQUEST_URI"];
  • step 2) parse the url with parse_url; this gives you an associative array with a path key: i.e. $parsed_url = parse_url($url);$path = $parsed_url['path'];
  • step 3) and this could be easy or hard. easy is to get the last component of the path. using preg_match. e.g.preg_match('//(.+)$/', $path, &$matches);
  • step 4) $matches returns an array that returns the entire match, plus the captured match. that is what you put in parentheses. you only have one captured match which is $matches[1];
  • step 5) you are done. $about = $matches[1];

learn more about preg_match here: https://www.php.net/preg_match

Upvotes: 1

Sergio
Sergio

Reputation: 1043

What you want to do is called Url Rewrite and can follow this guide to learn more.

If you look on the Internet, there are many examples.

Upvotes: 1

Tim
Tim

Reputation: 8606

The request url might include a query string. The easiest way to parse out just the path is to use parse_url.

echo parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH);
// prints "/about"

Upvotes: 1

Andy Lester
Andy Lester

Reputation: 93636

In PHP, use the parse_url function.

Perl: URI module.

Ruby: URI module.

.NET: 'Uri' class

Upvotes: 1

Quentin
Quentin

Reputation: 943099

$_SERVER['REQUEST_URI'] will contain the full URI. You can extract the bits you care about with a regular expression or parse_url.

Upvotes: 3

Related Questions