当名称作为变量而不是字符串文本传入时,PHP gethostbyname()返回Name而不是IP


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

PHP gethostbyname()在名称作为变量而不是字符串文字传入时返回Name而不是IP

我在一些有价值的讨论中看到了类似的问题,但没有看到这一点。

如果我向gethostbyname()传递一个变量,比如$domain,其中$domain是foreach循环创建的字符串值,那么返回值总是与我输入的值完全相同——例如,如果$domain=="google.com",则返回值是google.com。用字符串文字调用相同的函数gethostbyname(),我会得到IP地址。gethostbyname('google.com')

这是一个已知的bug吗?有变通办法吗?如果有任何帮助,我将不胜感激。

谢谢

此代码失败--为结果生成$url的值:

foreach ($this->domainNames as $url){
            $ips[]=gethostbyname($url); 
    }

第二组代码两次给出正确的ip地址($this->domainNames:中的每个值一次

foreach ($this->domainNames as $url){
            $ips[]=gethostbyname('google.com'); 
    }

解决方案:这是由于我的变量中出现了一些草率的空格,在创建$This->domainNames数组值时使用trim修复了这些空格。

gethostbyname()失败时,它将执行此操作。来自PHP手册:

失败时返回IPv4地址或包含未修改主机名的字符串。

你所说的不是真的。此:

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

输出:74.125.136.139两次

请提供$domainNames的转储,这样我们就可以看到实际发生了什么。