Rob
Rob

Reputation: 8101

Is it possible to resolve domain names to an IP address with PHP?

Well, very simple question. So that's good news for you, I guess.

More thorough explanation:

I have a PHP script allowing me to add urls to a database. I want the script to resolve the url to an IP address as well, to store that, too. However, some of the URLs are like this:

http://111.111.111.111/~example/index.php

So it also needs to work with that.

I'm not SURE that this is possible, but it only makes sense it would be.

So: Is it possible, and if so, how?

Upvotes: 2

Views: 2092

Answers (4)

Alix Axel
Alix Axel

Reputation: 154513

gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name.


Usage:

$ips = gethostbynamel('stackoverflow.com');

/*
Array
(
    [0] => 69.59.196.211
)
*/
echo '<pre>';
print_r($ips);
echo '</pre>';

$ips = gethostbynamel('google.com');

/*
Array
(
    [0] => 74.125.39.105
    [1] => 74.125.39.106
    [2] => 74.125.39.147
    [3] => 74.125.39.99
    [4] => 74.125.39.103
    [5] => 74.125.39.104
)
*/
echo '<pre>';
print_r($ips);
echo '</pre>';

To get the host out of an URL you can use this one liner:

// 111.111.111.111
echo parse_url('http://111.111.111.111/~example/index.php', PHP_URL_HOST);

Upvotes: 1

webbiedave
webbiedave

Reputation: 48897

gethostbyname

echo gethostbyname('stackoverflow.com'); // 69.59.196.211

You can use parse_url to grab the host from the url:

$urlParts = parse_url('http://111.111.111.111/~example/index.php'); 

print_r($urlParts);

/*
Array
(
    [scheme] => http
    [host] => 111.111.111.111
    [path] => /~example/index.php
)
*/

Upvotes: 3

user142162
user142162

Reputation:

gethostbyname()

$ip = gethostbyname('www.example.com');

It should be noted that if the website is on a shared hosting server, it is not guaranteed that your link will still be valid.

Upvotes: 1

Mitch Dempsey
Mitch Dempsey

Reputation: 39869

Yes, gethostbyname

http://us.php.net/manual/en/function.gethostbyname.php

Upvotes: 0

Related Questions