Using PHP to Perform DNS Lookups

Posted by Nessa | Posted in uncategorized | Posted on 30-06-2010

8

PHP has a couple DNS functions you can use to perform record lookups.

Most of us are familiar with the two basic ones – gethostbyname() and gethostbyaddr(), both of which perform a single function – returning a hostname or IP address. Here’s an example of both:

<?php

$ip = gethostbyname("v-nessa.net");
$host = gethostbyaddr("69.174.114.71");

echo "v-nessa.net has the IP $ip, which reverses to $host";
?>

The above will return:

v-nessa.net has the IP 69.174.114.71, which has a PTR of server.v-nessa.net

Similarly to gethostbyname, there’s gethostbynamel which is useful for hostnames with multiple A records:

$ips = gethostbynamel("test.v-nessa.net");
foreach ($ips as $ip => $value){
echo $value . "\n";
}

Will return:

69.174.114.71
69.174.115.243

A more advanced function is dns_get_record, which can pull any valid record for a hostname or IP.  Think about the dig command you use in Unix to find DNS records:

nessa@nessa-desktop:~$ dig +short v-nessa.net A
69.174.114.71

The dns_get_record function works in a similar way, and can obtain the following DNS record types:

DNS_A, DNS_CNAME, DNS_HINFO, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA, DNS_TXT, DNS_AAAA, DNS_SRV, DNS_NAPTR, DNS_A6, DNS_ALL or DNS_ANY.

The following will give you a similar result:

$recs = dns_get_record("v-nessa.net", DNS_A);
print_r($recs);

Will return:

Array
(
[0] => Array
(
[host] => v-nessa.net
[type] => A
[ip] => 69.174.114.71
[class] => IN
[ttl] => 13728
)
)

If you want to obtain multiple DNS types, you can do so by separating the record types with a plus sign:

$recs = dns_get_record("v-nessa.net", DNS_A + DNS_MX);

Will return:

Array
(
[0] => Array
(
[host] => v-nessa.net
[type] => A
[ip] => 69.174.114.71
[class] => IN
[ttl] => 13736
)

[1] => Array
(
[host] => v-nessa.net
[type] => MX
[pri] => 0
[target] => v-nessa.net
[class] => IN
[ttl] => 14145
)

)

You’ll notice that the output is a double array, so to call individual values you can do either of the following:

// will return the IP for array 0 ( A record)

echo $recs[0]['ip'];

// will return results for common records

foreach ($recs as $type => $value){
echo $value[ip] . "\n";
}

Similar to the example above, you can use the DNS_ALL type to show any records available for the hostname, and use a minus sign to exclude certain record types. For example, the below code will return all DNS results for v-nessa.net, but exclude NS records:

$recs = dns_get_record("v-nessa.net", DNS_ALL - DNS_NS );

foreach ($recs as $type => $value){
echo $value[type] . "\n";
}

The following records were returned:

A
SOA
MX
TXT

Here’s a more practical example – a simple PHP DNS lookup script. Say you have a form on your site that allows a user to type in a hostname and select a type of record: A, MX, NS, and TXT. The passed form values are $host and $type, and the below script will accept the variables and output the results according to the record type:

HTML Form:

<form action="dns.php" method="POST">
Hostname: <input type="text" name="host" />
Type: <select name="type">
<option value="a">A</option>
<option value="mx">MX</option>
<option value="ns">NS</option>
<option value="txt">TXT</option> </select>
</form>

PHP Script (dns.php):

<?php

if(!empty($_POST['host']) && !empty($_POST['type'])){

    // Grab variable from form and define valid types

    $host = $_POST['host'];
    $type = strtoupper($_POST['type');
    $validtypes=array("A","MX","NS","TXT");

    // Check that dns type is defined or allowed

    if(!defined("DNS_" . $type) or !in_array($type,$validtypes)){
       echo "Invalid DNS Type!";
    }else{

       $type = constant("DNS_" . $type);
       $rec = dns_get_record($host, $type);

       // Set result types - can be modified by using available elements from $rec array

       switch($type){
             case DNS_A:
                    $recvals=array("Hostname" => "host","Type" => "type", "IP" => "ip");
                    break;
             case DNS_MX:
                    $recvals=array("Hostname" => "host","Type" => "type", "Target" => "target", "Priority" => "pri");
                    break;
             case DNS_NS:
                    $recvals=array("Hostname" => "host","Type" => "type", "Target" => "target");
                    break;
             case DNS_TXT:
                    $recvals=array("Hostname" => "host","Type" => "type", "Record" => "txt");
                    break;
        }

      // Output results

      foreach ($rec as $arr => $num){
             foreach ($recvals as $title => $value){
                    echo $title . " : " . $num[$value] . "\n";
             }
      }

    }
} else {

     echo "Either hostname or record type is missing";
}

It’s of course easy to modify the above code accordingly, and I’m sure there may be better ways to do this. Feel free to post your own code snippets or comments.

This Week’s Sexy Articles

Posted by Nessa | Posted in uncategorized | Posted on 04-06-2010

0

The Developer Obsession with Code Names – Pingdom

Website feeling overweight? Slim it down with Smush.it – Diary of a Ninja

Really Useful Tutorials You Should Have Read in May 2010 – W3 Avenue

Beautiful and Useful 404 Error Pages for Inspiration – 6 Revisions

15 Great Content Management Systems for Designers – Design Tutorials 4 U

10 Easy Solutions for PHP String Manipulation – PHP Builder

12 Cross-Browser Compatibility Tools for Designers – Web Hosting Help Guy

The Fine Line Between Spam and Email Marketing

Posted by Nessa | Posted in uncategorized | Posted on 03-06-2010

6

If I had a Viagra pill for every time I confronted a spammer who pulled the “email marketing” excuse…

There’s no debate, no exceptions, and no justification. If you’re sending out massive amounts of unsolicited email, you’re a spammer. Period.  You’re not running a legitimate or respected marketing campaign, you’re not helping anyone with their emotional or erectile dysfunction problems, and in reality, no one cares to read what you have to say.

A lot of hosting providers are cracking down on spammers – and from experience, I can tell you why:  Spammers are an inconvenience to everyone – even themselves. They are an inconvenience to me, the system administrator that has to sift through spam complaints and spend hours every week tracking them down.  They are an inconvenience to our customers, who find their email being blacklisted because of a spammer on their network. And finally, they are an inconvenience to you, the Internet user, that has to deal with getting spam on a daily basis because some people have nothing better to do.

And here’s how you know if you’re one of those some people:

  • You purposely find ways to circumvent your ISP or host’s mailing limits instead of simply asking
  • You’re harvesting or purchasing email addresses off of websites, other mailing lists, or third parties to compose your recipient base
  • You’re sending those people [unsolicited] email advertising yourself, a product, or a website
  • You use spoofing or other tactics to hide your email address or server information
  • You don’t give your victims recipients a way to opt out of your torturous email campaigns
  • You hide behind the CAN SPAM law to justify your behavior
  • You get the slight inkling that people hate you for what you do

So what’s the fine line between spam and email marketing?

It’s all about honesty and consent.  If I contact a fellow blog owner requesting a link exchange, I wouldn’t technically consider that spam. If I send the same email to 40 other people, I’m crossing the line.  A legitimate, non-spammy email campaign would consist of a database of opted-in users, and email content consistent with what those users requested to be in the loop for.  If any of those users decide they don’t want to participate anymore, they are given a quick and easy way to remove themselves from the list.  The fine line between spamming and email marketing is the concept of opting in. Simply put, email marketers use opt-in lists, spammers don’t.

And no, I’m not talking about purchasing opt-in lists that other people have compiled.

Spammers have ruined the concept of email marketing enough to where now even legitimate email marketers are being accused of spamming, and many hosts won’t even work with them.  That’s not all hosts are doing to fight back, either.  Many larger hosting providers are so tired of dealing with spammers on their network that they impose mailing limitations that tend to inconvenience other users. Here are just a few:

  • Limiting the number of emails sent per minute, hour, or day
  • Limiting the number of recipients that can exist in a single email or BCC field
  • Locking outbound SMTP connections so scripts can’t send email from remote servers
  • Blocking email sent from certain system users (like the Apache user), requiring the use of authenticated mail sessions

For everyone else, here are a few tips on dealing with SPAM:

  • Delete it – it takes two seconds
  • Learn what a spam filter is, and use it
  • Stop trying to play Internet police. Feel free to report spam to the ISP or host, but don’t start spouting off with legal threats. It’s not going to change the fact that millions of spam emails are sent every day, and no court is going to waste their time on you
  • Don’t assume that the ISP or host can read minds – do you think they would have intentionally allowed a spammer to sign up for their service?

And for ISP’s and hosts, you have responsibilities as well:

  • Don’t be afraid to impose the aforementioned limitations on your servers. Your goal should be to look out for the best interests of your customers as a whole
  • Require justification from users that want to send large mailing lists, asking them how much email they are sending, who they are sending to, and whether they have an opt-in/out method
  • Set up abuse@ and postmaster@ email addresses, which will usually be where complaints are sent to. This way you’re aware of users that may be abusing your network, even if
  • Sign up for feedback loops, so automated spam reports from various email providers are sent to you to review
  • Deal with spammers ASAP. Not doing so can end up causing your network to get blacklisted, or have complaints escalated to cancellations from your customers – or even legal threats