Search code examples
phpgethostbyname

PHP gethostbyname() returning Name instead of IP when the name is passed in as a variable rather than a string literal


PHP gethostbyname() returning Name instead of IP when the name is passed in as a variable rather than a string literal

I have seen similar problems with some valuable discussion but nothing that this this head on.

If I pass a varible say $domain to gethostbyname() where $domain is the string value created by a foreach loop, the return value is always exactly what I put into to it -- for example if $domain =="google.com" the return value is google.com. Calling the same function gethostbyname() with a string literal I get the IP address. gethostbyname('google.com')

Is this a known bug? Is there a workaround? I'll be grateful for any help.

Thank you

This code fails -- producing the value of $url for a result:

foreach ($this->domainNames as $url){

            $ips[]=gethostbyname($url); 

    }

The second set of code gives the correct ip address twice (once for each value in $this->domainNames:

foreach ($this->domainNames as $url){

            $ips[]=gethostbyname('google.com'); 

    }

SOLUTION: This turned out to be caused some some sloppy spaces in my varible which were fixed using trim when creating my $this->domainNames array values.


Solution

  • It will do this when gethostbyname() fails. From the PHP manual:

    Returns the IPv4 address or a string containing the unmodified hostname on failure.

    What you are claiming is not true. This:

    <?php
    $domainNames = array("google.com", "google.com");
    
    foreach ($domainNames as $url){
        echo gethostbyname($url); 
    }   
    

    Outputs: 74.125.136.139 twice

    Please provide a dump of $domainNames, so we can see what is really happening.