Returning array of nameservers for domain php

怎甘沉沦 提交于 2019-12-25 03:57:12

问题


I want to return the nameservers of a domain in php, however I'm only getting one nameserver put in the array.

This is the code I am using:

//get auth ns datat
$authnsData = dns_get_record($domain, DNS_NS);

//put the results into a nice array
foreach ($authnsData as $nsinfo)
{
    $authns = array(
        'nsdata' => array(
            'nameserver' => $nsinfo['target'],
            'ip' => $this->getnsIP($nsinfo['target']),
            'location' => $this->getipLocation($this->getnsIP($nsinfo['target'])),
         ),
    );

    return $authns;
}

The result I'm getting is:

Array
(
    [nsdata] => Array
        (
            [nameserver] => ns-us.1and1-dns.org
            [ip] => 217.160.83.2
            [location] => 
        )

)

Lets say a domain has 2 or more nameservers, I'm only getting one of those added to the array.

If you would like to test it out to find out the issue, the code is in this file: https://github.com/Whoisdoma/core/blob/master/src/Whoisdoma/Controllers/DNSWhoisController.php#L38

The function is getAuthNS, and LookupAuthNS. Before anyone suggests using a for loop, I have tried a for ($num = 0;) type loop.


回答1:


  1. You're returning too early, so that your loop only ever runs a single iteration.
  2. You're assigning a new array to $authns in every iteration, instead of pushing into it.

Try this piece of code instead:

foreach ($authnsData as $nsinfo)
{
    $authns[] = [
        'nsdata' => [
            'nameserver' => $nsinfo['target'],
            'ip'         => $this->getnsIP($nsinfo['target']),
            'location'   => $this->getipLocation($this->getnsIP($nsinfo['target'])),
         ],
    ];
}

return $authns;

BTW, there's no need to run getnsIP twice. You can use this instead:

foreach ($authnsData as $nsinfo)
{
    $nameserver = $nsinfo['target'];
    $ip         = $this->getnsIP($nameserver);
    $location   = $this->getipLocation($ip);

    $authns[] = ['nsdata' => compact('nameserver', 'ip', 'location')];
}

return $authns;


来源:https://stackoverflow.com/questions/24476786/returning-array-of-nameservers-for-domain-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!