Php получить адрес домена

gethostbyname

Возвращает адрес IPv4 или строку, содержащую неизмененный hostname в случае возникновения ошибки.

Примеры

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

$ip = gethostbyname ( ‘www.example.com’ );

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

  • gethostbyaddr() — Получает доменное имя хоста, соответствующее переданному IP-адресу
  • gethostbynamel() — Получает список IPv4-адресов, соответствующих переданному доменному имени хоста
  • inet_pton() — Конвертирует читаемый IP-адрес в его упакованное представление in_addr
  • inet_ntop() — Конвертирует упакованный интернет-адрес в читаемый формат

User Contributed Notes 30 notes

If you do a gethostbyname() and there is no trailing dot after a domainname that does not resolve, this domainname will ultimately be appended to the server-FQDN by nslookup.

So if you do a lookup for nonexistentdomainname.be your server may return the ip for nonexistentdomainname.be.yourhostname.com, which is the server-ip.

To avoid this behaviour, just add a trailing dot to the domainname; i.e. gethostbyname(‘nonexistentdomainname.be.’)

This function says «Returns the IPv4 address or a string containing the unmodified hostname on failure.

This isn’t entirely true, any hostname with a null byte in it will only return the characters BEFORE the null byte.

$hostname = «foo\0bar» ;
var_dump ( $hostname );
var_dump ( gethostbyname ( $hostname ));
?>

Results:
string ‘foo�bar’ (length=7)
string ‘foo’ (length=3)

Important note: You should avoid its use in production.

DNS Resolution may take from 0.5 to 4 seconds, and during this time your script is NOT being executed.

Your customers may think that the server is slow, but actually it is just waiting for the DNS resolution response.

You can use it, but if you want performance, you should avoid it, or schedule it to some CRON script.

Options for the underlying resolver functions can be supplied by using the RES_OPTIONS environmental variable. (at least under Linux, see man resolv.conf)

Set timeout and retries to 1 to have a maximum execution time of 1 second for the DNS lookup:
putenv ( ‘RES_OPTIONS=retrans:1 retry:1 timeout:1 attempts:1’ );
gethostbyname ( $something );
?>

You should also use fully qualified domain names ending in a dot. This prevents the resolver from walking though all search domains and retrying the domain with the search domain appended.

For doing basic RBL (Real Time Blacklist) lookups with this function do:

Читайте также:  Php projects with documentation

$host = ‘64.53.200.156’ ;
$rbl = ‘sbl-xbl.spamhaus.org’ ;
// valid query format is: 156.200.53.64.sbl-xbl.spamhaus.org
$rev = array_reverse ( explode ( ‘.’ , $host ));
$lookup = implode ( ‘.’ , $rev ) . ‘.’ . $rbl ;
if ( $lookup != gethostbyname ( $lookup )) echo «ip: $host is listed in $rbl \n» ;
> else echo «ip: $host NOT listed in $rbl \n» ;
>
?>

Tomas V.V.Cox

gethostbyname and gethostbynamel does not ask for AAAA records. I have written two functions to implement this. gethostbyname6 and gethostbynamel6. I don’t believe this issue has been addressed yet.

They are made to replace gethostbyname[l], in a way that if $try_a is true, if it fails to get AAAA records it will fall back on trying to get A records.

Feel free to correct any errors, I realise that it is asking for *both* A and AAAA records, so this means two DNS calls.. probably would be more efficient if it checked $try_a before making the query, but this works for me so I’ll leave that up to someone else to implement in their own work.. the tip is out there now anyway..

function gethostbyname6($host, $try_a = false) // get AAAA record for $host
// if $try_a is true, if AAAA fails, it tries for A
// the first match found is returned
// otherwise returns false

function gethostbynamel6($host, $try_a = false) // get AAAA records for $host,
// if $try_a is true, if AAAA fails, it tries for A
// results are returned in an array of ips found matching type
// otherwise returns false

$dns6 = dns_get_record($host, DNS_AAAA);
if ($try_a == true) $dns4 = dns_get_record($host, DNS_A);
$dns = array_merge($dns4, $dns6);
>
else < $dns = $dns6; >
$ip6 = array();
$ip4 = array();
foreach ($dns as $record) if ($record[«type»] == «A») $ip4[] = $record[«ip»];
>
if ($record[«type»] == «AAAA») $ip6[] = $record[«ipv6»];
>
>
if (count($ip6) < 1) if ($try_a == true) if (count($ip4) < 1) return false;
>
else return $ip4;
>
>
else return false;
>
>
else return $ip6;
>
>

When using gethostbynamel() and gethostbyname() together, you must do gethostbynamel() first, otherwise it will always give you one IP (or none) from the cache, and not return the full lookup.

On a side-note, PHP (5.0.4, but probably other versions too) can cache gethostbyname information.

In short, once PHP looks up an address, it may not actually perform another lookup as you may expect. In my particular case (I think) the problem was a change to resolv.conf didn’t take effect inside PHP (although nslookup/ping etc worked fine). Stop/Starting Apache fixed it (although a simple ‘restart’ (kill -HUP) didn’t).

Читайте также:  Python with open закрыть файл

In short, if you change resolv.conf, stop and restart Apache.

In PHP4 you can use gethostbyname() but I have found this unreliable when doing lookups on entries that return A records on the private network. PHP5 has a much better routine — dns_get_record(). If you are stuck with PHP4 or don’t want to upgrade you can use dig:

Источник

How to get the current domain name using PHP

The $_SERVER array is a global variable that contains server and header information.

To get the domain name where you run PHP code, you need to access the SERVER_NAME or HTTP_HOST index from the $_SERVER array.

Suppose your website has the URL of https://example.com/post/1 . Here’s how you get the domain name:

If you are using Apache server 2, you need to configure the directive UseCanonicalName to On and set the ServerName .

Otherwise, the ServerName value reflects the hostname supplied by the client, which can be spoofed.

Aside from the SERVER_NAME index, you can also get the domain name using HTTP_HOST like this:

The difference is that HTTP_HOST is controlled from the browser, while SERVER_NAME is controlled from the server.

If you need the domain name for business logic, you should use SERVER_NAME because it is more secure.

Finally, you can combine SERVER_NAME with HTTPS and REQUEST_URI indices to get your website’s complete URL.

See the code example below:

Now you’ve learned how to get the domain name of your website using PHP. Nice!

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

How to get the domain name from a URL string using PHP

To get the domain name from a full URL string in PHP, you can use the parse_url() function.

The parse_url() function returns various components of the URL you passed as its argument.

The domain name will be returned under the host key as follows:

Читайте также:  PHP Database Connection Test

But keep in mind that the parse_url function will return any subdomain you have in your URL.

Consider the following examples:

The same goes for any kind of subdomains your URL may have:

If you want to remove the subdomain from your URL, then you need to use the PHP Domain Parser library.

The PHP Domain Parser can parse a complex domain name that a regex can’t parse.

Use this library in combination with parse_url() to get components of your domain name as shown below:

You need to have a copy of public_suffix_list.dat that you can download from publicsuffix.org.

To get google.co.uk from the URL, call the registrableDomain() function from the resolved domain name.

You can see the documentation for PHP Domain Parser on its GitHub page.

Now you’ve learned how to get the domain name from a URL using PHP. Nice work!

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Search

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

How to Get Domain Name from URL in PHP

Parse domain name from URL is used in many cases in the web project. In this short tutorial, we’ll provide a simple code snippet to get domain name from URL in PHP. Using our example script, you’ll be able to extract only the domain name from any type of URL.

All PHP code are group together in getDomain() function. The $url param should be passed to getDomain() function, from which you want to get the domain name. getDomain() function returns the domain name if found and FALSE if not found.

function getDomain($url) $pieces = parse_url($url); 
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if(
preg_match('/(?P[a-z0-9][a-z0-9\-]\.[a-z\.])$/i', $domain, $regs)) return $regs['domain'];
>
return
FALSE;
>

echo
getDomain("http://example.com"); // outputs 'example.com'
echo getDomain("http://www.example.com"); // outputs 'example.com'
echo getDomain("http://mail.example.co.uk"); // outputs 'example.co.uk'

How to Configure PayPal Auto Return and Payment Data Transfer on Business Account arrow_forward

Источник

Оцените статью