Brandon Braner
Brandon Braner

Reputation: 93

ping domain name to get ip with php

so im probably dumb and this is probably very simple. I have a text file with around 300 domain names in it. I dont want to ping them manual so I am working on a simple little php script to ping the domain name return the ip address and then echo them

I have the domains in a text file i can read the file and output thenames but the second i try to ping them all i get is a blank list of

  • dots like i said probably missing somthing so dumb but I appreciate any help

     <?php
    
     $names = file('sites.txt');
     foreach ($names as $name) {
     $testping = exec("ping  $name");
      echo '<li>' . $testping . '</li>';
     }
    
      ?>
    

    new code**

     $names = file('sites.txt');
     foreach ($names as $name) {
    
       $ip = gethostbyname($name);
    
    
    
      echo '<li>' . $ip . '</li>';
      }
    
       ?>
    

    Upvotes: 1

    Views: 11331

  • Answers (3)

    Mike B
    Mike B

    Reputation: 32145

    If your end-goal is to get the ip address look into gethostbyname():

    $names = file('sites.txt');
     foreach ($names as $name) {
         $ip = gethostbyname($name);
         echo '<li>' . $ip. '</li>';
     }
    

    echo $ip;
    

    Upvotes: 6

    Jay Versluis
    Jay Versluis

    Reputation: 2072

    @BrandonBraner Exactly what I wanted to do too! The reason why only the last entry in the list works is because PHP reads the lines correctly but appends a character at the end. It doesn't do this for the last line - don't ask me why. Perhaps it's the new line character.

    To get round it, use substr:

        $names = file('mysites.txt');
    foreach ($names as $name) {
    
       $mydomain = substr($name, 0, -1);
       $ip = gethostbyname($mydomain);
    
      echo '<li>' . $ip . '</li>';
      }
    

    Did the trick for me. All you then need to do is to add an empty last line in the list of domains.

    Upvotes: 0

    aynber
    aynber

    Reputation: 23009

    gethostbyname() will return the IP address for any domain you enter. http://php.net/manual/en/function.gethostbyname.php

    Upvotes: 1

    Related Questions