paulalexandru paulalexandru - 4 months ago 9
PHP Question

Get base website URL from input

I have a textbox on my website where peoples can submit url addresses. Most of the time the enter wrong url's like:

http://www.website.com?id=1
http://www.website.com/#/gls
http://www.website.com/post/test


But I want them to enter their base url, meaning this: http://www.website.com

How can I achieve this considering that I have their url address stored in an
$url
variable?

I have some ideeas but I don't think it's a very good solution. For example I thought at splitting the domain after "." and after that get the domain extension somehow without the rest of the useles code.

Answer

You could use parse_url rather than a regular expression, to take out the parts you need and compare it to what they've entered like this:

// Get each part of the URL
$parts = parse_url($url);

// Rebuild the URL with only the scheme and domain (Without path, fragment, query string etc.)
$expected = $parts['scheme'] . '://' . $parts['host'];

// Compare the expected URL with what they user has entered.
if ($expected != $url) {
    // Do something
}
Comments