php get domain from url

Get domain from URL

OK, before you say «oh, come on! this is easy», I must inform you that I’ve been testing many many different methods for that specific thing, for a long time, and I haven’t found any that really works for any url, and any domain.

Examples :

So, any ideas? Do you know of any working function/script?

To anyone interested : Please have a look at @bystwn22‘s answer. It’s one of the smoothest working solutions you could possibly find! 🙂

php get domain from url. Смотреть фото php get domain from url. Смотреть картинку php get domain from url. Картинка про php get domain from url. Фото php get domain from url

3 Answers 3

Okay try this, i know the question is really tricky :\

php get domain from url. Смотреть фото php get domain from url. Смотреть картинку php get domain from url. Картинка про php get domain from url. Фото php get domain from url

I worked on a simpler solution. Due to the issues we faced with parse_url

Well you actually need 2 lists: second level domains and top level domains.

Get host from your url with preg_match or parse_url, lets say it will be subdomain.domain.org.uk

Otherwise your domain is what you’ve checked in the step 2 (if last element of array is one of top level domains, you can skip this check if you are pretty sure the domain is valid). If your original host was subdomain.domain.com, then you have checked that domain.com is not a second-level domain, that means domain.com is what you were looking for.

Here is the list of second-level domains. Or you can try to find a better one.

Источник

How to get the base domain name from an URL using PHP?

I need to get the domain name from an URL. The following examples should all return google.com :

I’m hesitant to use Regular Expressions, because something like domain.com/google.com could return incorrect results.

How can I get the top-level domain, using PHP? This needs to work on all platforms and hosts.

php get domain from url. Смотреть фото php get domain from url. Смотреть картинку php get domain from url. Картинка про php get domain from url. Фото php get domain from url

7 Answers 7

The best way I can think of is to have a mapping of all the TLDs that you want to handle, since certain TLDs can be tricky (co.uk).

top-level domains and second-level domains may be 2 characters long but a registered subdomain must be at least 3 characters long.

EDIT: because of pjv’s comment, i learned Australian domain names are an exception because they allow 5 TLDs as SLDs (com,net,org,asn,id) example: somedomain.com.au. i’m guessing com.au is nationally controlled domain name which «shares». so, technically, «com.au» would still be the «base domain», but that’s not useful.

«co.uk» is NOT a valid host because there is no valid domain name

going with that assumption this function will return the proper «basedomain» in almost all cases, without requiring a «url map».

if you happen to be one of the rare cases, perhaps you can modify this to fulfill particular needs.

EDIT: you must pass the domain string as a URL with it’s protocol (http://, ftp://, etc) or parse_url() will not consider it a valid URL (unless you want to modify the code to behave differently)

if you need to be accurate use fopen or curl to open this URL: http://data.iana.org/TLD/tlds-alpha-by-domain.txt

then read the lines into an array and use that to compare the domain parts

EDIT: to allow for Australian domains:

Источник

parse_url

(PHP 4, PHP 5, PHP 7, PHP 8)

parse_url — Разбирает URL и возвращает его компоненты

Описание

Эта функция разбирает URL и возвращает ассоциативный массив, содержащий все компоненты URL, которые в нём присутствуют. Элементы массива не будут декодированы как URL.

Эта функция не предназначена для проверки на корректность данного URL, она только разбивает его на нижеперечисленные части. Частичные и недопустимые URL также принимаются, parse_url() пытается сделать всё возможное, чтобы разобрать их корректно.

Список параметров

Возвращаемые значения

Примеры

Пример #1 Пример использования parse_url()

Результат выполнения данного примера:

Пример #2 Пример использования parse_url() при отсутствии протокола

Результат выполнения данного примера:

Примечания

Эта функция может выдать некорректный результат для относительных URL.

Эта функция предназначена специально для разбора URL-адресов, а не URI. Однако, чтобы соответствовать требованиям обратной совместимости PHP, она делает исключение для протокола file://, в которой допускаются тройные слеши (file:///. ). Для любого другого протокола это недопустимо.

Смотрите также

User Contributed Notes 33 notes

[If you haven’t yet] been able to find a simple conversion back to string from a parsed url, here’s an example:

Here is utf-8 compatible parse_url() replacement function based on «laszlo dot janszky at gmail dot com» work. Original incorrectly handled URLs with user:pass. Also made PHP 5.5 compatible (got rid of now deprecated regex /e modifier).

Here’s a good way to using parse_url () gets the youtube link.
This function I used in many works:

I was writing unit tests and needed to cause this function to kick out an error and return FALSE in order to test a specific execution path. If anyone else needs to force a failure, the following inputs will work:

There’s a quirk where this function will return the host as the «path» if there is a leading space.

I have coded a function which converts relative URL to absolute URL for a project of mine. Considering I could not find it elsewhere, I figured I would post it here.

The following function takes in 2 parameters, the first parameter is the URL you want to convert from relative to absolute, and the second parameter is a sample of the absolute URL.

Currently it does not resolve ‘../’ in the URL, only because I do not need it. Most webservers will resolve this for you. If you want it to resolve the ‘../’ in the path, it just takes minor modifications.

?>

OUTPUTS:
http :// user:pass@example.com:8080/path/to/index.html
http :// user:pass@example.com:8080/path/to/img.gif
http :// user:pass@example.com:8080/img.gif
http :// user:pass@example.com:8080/path/to/img.gif
http :// user:pass@example.com:8080/path/to/../img.gif
http :// user:pass@example.com:8080/path/to/images/img.gif
http :// user:pass@example.com:8080/images/img.gif
http :// user:pass@example.com:8080/path/to/images/img.gif
http :// user:pass@example.com:8080/path/to/../images/img.gif

Sorry if the above code is not your style, or if you see it as «messy» or you think there is a better way to do it. I removed as much of the white space as possible.

Источник

Parsing domain from a URL

I need to build a function which parses the domain from a URL.

it should return google.com

php get domain from url. Смотреть фото php get domain from url. Смотреть картинку php get domain from url. Картинка про php get domain from url. Фото php get domain from url

18 Answers 18

parse_url doesn’t handle really badly mangled urls very well, but is fine if you generally expect decent urls.

This would return the google.com for both http://google.com/. and http://www.google.com/.

for some odd reason, parse_url returns the host (ex. example.com) as the path when no scheme is provided in the input url. So I’ve written a quick function to get the real host:

The code that was meant to work 100% didn’t seem to cut it for me, I did patch the example a little but found code that wasn’t helping and problems with it. so I changed it out to a couple of functions (to save asking for the list from Mozilla all the time, and removing the cache system). This has been tested against a set of 1000 URLs and seemed to work.

I know I should have turned this into a class, but didn’t have time.

But if you want extract domain or its parts, you need package that using Public Suffix List. Yes, you can use string functions arround parse_url(), but it will produce incorrect results sometimes.

I recomend TLDExtract for domain parsing, here is sample code that show diff:

php get domain from url. Смотреть фото php get domain from url. Смотреть картинку php get domain from url. Картинка про php get domain from url. Фото php get domain from url

I’ve found that @philfreo’s solution (referenced from php.net) is pretty well to get fine result but in some cases it shows php’s «notice» and «Strict Standards» message. Here a fixed version of this code.

php get domain from url. Смотреть фото php get domain from url. Смотреть картинку php get domain from url. Картинка про php get domain from url. Фото php get domain from url

Please consider replacring the accepted solution with the following:

parse_url() will always include any sub-domain(s), so this function doesn’t parse domain names very well. Here are some examples:

Finally, Jeremy Kendall’s PHP Domain Parser allows you to parse the domain name from a url. League URI Hostname Parser will also do the job.

You can pass PHP_URL_HOST into parse_url function as second parameter

php get domain from url. Смотреть фото php get domain from url. Смотреть картинку php get domain from url. Картинка про php get domain from url. Фото php get domain from url

Here is the code i made that 100% finds only the domain name, since it takes mozilla sub tlds to account. Only thing you have to check is how you make cache of that file, so you dont query mozilla every time.

For some strange reason, domains like co.uk are not in the list, so you have to make some hacking and add them manually. Its not cleanest solution but i hope it helps someone.

parse_url didn’t work for me. It only returned the path. Switching to basics using php5.3+:

I have edited for you:

All type url (www.domain.ltd, sub1.subn.domain.ltd will result to : domain.ltd.

php get domain from url. Смотреть фото php get domain from url. Смотреть картинку php get domain from url. Картинка про php get domain from url. Фото php get domain from url

I’m adding this answer late since this is the answer that pops up most on Google.

You can use PHP to.

to grab the host but not the private domain to which the host refers. (Example www.google.co.uk is the host, but google.co.uk is the private domain)

To grab the private domain, you must need know the list of public suffixes to which one can register a private domain. This list happens to be curated by Mozilla at https://publicsuffix.org/

The below code works when an array of public suffixes has been created already. Simply call

Источник

Extract domain, path etc from a full url with PHP

PHP’s parse_url function makes it easy to extract the domain, path and other useful bits of information from a full URL. This can be useful for a variety of purposes, such as when spidering content from a website and needing to extract particular pieces of information from the links in the page.

Returning an associative array

The parse_url function takes the url as the first argument and an optional component value as the second argument. If the second argument is omitted then it returns the found values as an associative array.

This post is at https://www.electrictoolbox.com/php-extract-domain-from-full-url/ and getting the associative array of information from it is done like this:

Then doing print_r($parts) will output this:

If they are present, the array will also contain values for port, user, pass (i.e. password), query (the query string component of the URL) and fragment (the part after the #).

Returning a string

If all you are after is a single component from the array as a single string, pass the second «component» parameter from the following constants: PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT.

To just get the domain from this blog post’s URL, do this:

PHP Documentation

For more information read the PHP manual page for this function.

Follow up posts

Have a read of my post titled «PHP: get keywords from search engine referer url» to find out how to use the parse_url function in conjunction with the parse_str function to see what query string visitors have entered into a search engine.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *