<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">

<channel>
	<title>Web Design, Marketing, SEO &amp; Clean CSS | SOAPTRAY</title>
	
	<link>http://www.soaptray.com/blog</link>
	<description>A fresh look at Design, SEO, CSS &amp; Programming</description>
	<pubDate>Mon, 25 Aug 2008 18:20:49 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/soaptray" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="soaptray" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">soaptray</feedburner:emailServiceId><feedburner:feedburnerHostname xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>PHP Domain Availability Lookup</title>
		<link>http://www.soaptray.com/blog/2008/08/php-domain-availability-lookup/</link>
		<comments>http://www.soaptray.com/blog/2008/08/php-domain-availability-lookup/#comments</comments>
		<pubDate>Mon, 25 Aug 2008 03:06:57 +0000</pubDate>
		<dc:creator>Regan Johnson</dc:creator>
		
		<category><![CDATA[PHP &amp; MySQL]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Tutorials]]></category>

		<category><![CDATA[classes]]></category>

		<category><![CDATA[domain]]></category>

		<category><![CDATA[object oriented programming]]></category>

		<category><![CDATA[oop]]></category>

		<category><![CDATA[php]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[whois]]></category>

		<guid isPermaLink="false">http://www.soaptray.com/?p=13</guid>
		<description><![CDATA[The process to check if a domain name is registered or not usually involves a series of steps that can be tedious and time consuming. In this article, I will show you how to create your own domain name availability script using PHP that you may use in your personal projects – it&#8217;s much easier [...]]]></description>
			<content:encoded><![CDATA[<p>The process to check if a domain name is registered or not usually involves a series of steps that can be tedious and time consuming. In this article, I will show you how to create your own domain name availability script using PHP that you may use in your personal projects – it&#8217;s much easier than you might think.</p>
<h2>Building the Domain Name Availability class</h2>
<p>For the sake of this article, let&#8217;s call this class &#8220;whois&#8221;.</p>
<pre>class whois {

}</pre>
<p>One of the first things we are going to add to our class is a list of the common <abbr title="Top Level Domain Names">TLD</abbr>, which will include which whois server to use for each domain, and the associated text to search for if a domain is available or not. The array is named &#8220;$ext&#8221; which is short for extensions.</p>
<pre>public $ext = array(
'.com' =&gt; array('whois.crsnic.net','No match for'),
'.net' =&gt; array('whois.crsnic.net','No match for'),
'.org' =&gt; array('whois.publicinterestregistry.net','NOT FOUND'),
'.us' =&gt; array('whois.nic.us','Not Found'),
'.biz' =&gt; array('whois.biz','Not found'),
'.info' =&gt; array('whois.afilias.net','NOT FOUND'),
'.eu' =&gt; array('whois.eurid.eu','FREE'),
'.mobi' =&gt; array('whois.dotmobiregistry.net', 'NOT FOUND'),
'.tv' =&gt; array('whois.nic.tv', 'No match for'),
'.in' =&gt; array('whois.inregistry.net', 'NOT FOUND'),
'.co.uk' =&gt; array('whois.nic.uk','No match'),
'.co.ug' =&gt; array('wawa.eahd.or.ug','No entries found'),
'.or.ug' =&gt; array('wawa.eahd.or.ug','No entries found'),
'.sg' =&gt; array('whois.nic.net.sg','NOMATCH'),
'.com.sg' =&gt; array('whois.nic.net.sg','NOMATCH'),
'.per.sg' =&gt; array('whois.nic.net.sg','NOMATCH'),
'.org.sg' =&gt; array('whois.nic.net.sg','NOMATCH'),
'.com.my' =&gt; array('whois.mynic.net.my','does not Exist in database'),
'.net.my' =&gt; array('whois.mynic.net.my','does not Exist in database'),
'.org.my' =&gt; array('whois.mynic.net.my','does not Exist in database'),
'.edu.my' =&gt; array('whois.mynic.net.my','does not Exist in database'),
'.my' =&gt; array('whois.mynic.net.my','does not Exist in database'),
'.nl' =&gt; array('whois.domain-registry.nl','not a registered domain'),
'.ro' =&gt; array('whois.rotld.ro','No entries found for the selected'),
'.com.au' =&gt; array('whois.ausregistry.net.au','No data Found'),
'.ca' =&gt; array('whois.cira.ca', 'AVAIL'),
'.org.uk' =&gt; array('whois.nic.uk','No match'),
'.name' =&gt; array('whois.nic.name','No match'),
'.ac.ug' =&gt; array('wawa.eahd.or.ug','No entries found'),
'.ne.ug' =&gt; array('wawa.eahd.or.ug','No entries found'),
'.sc.ug' =&gt; array('wawa.eahd.or.ug','No entries found'),
'.ws' =&gt; array('whois.website.ws','No Match'),
'.be' =&gt; array('whois.ripe.net','No entries'),
'.com.cn' =&gt; array('whois.cnnic.cn','no matching record'),
'.net.cn' =&gt; array('whois.cnnic.cn','no matching record'),
'.org.cn' =&gt; array('whois.cnnic.cn','no matching record'),
'.no' =&gt; array('whois.norid.no','no matches'),
'.se' =&gt; array('whois.nic-se.se','No data found'),
'.nu' =&gt; array('whois.nic.nu','NO MATCH for'),
'.com.tw' =&gt; array('whois.twnic.net','No such Domain Name'),
'.net.tw' =&gt; array('whois.twnic.net','No such Domain Name'),
'.org.tw' =&gt; array('whois.twnic.net','No such Domain Name'),
'.cc' =&gt; array('whois.nic.cc','No match'),
'.nl' =&gt; array('whois.domain-registry.nl','is free'),
'.pl' =&gt; array('whois.dns.pl','No information about'),
'.pt' =&gt; array('whois.dns.pt','No match')
);</pre>
<p>We will also define our error variable that we will be using in this class.</p>
<pre>public $error;</pre>
<h2>Building the Methods</h2>
<p>Now that we have our class ready to go, and our list of domain name extensions and associated WHOIS servers, lets build the function to use this information to perform the domain name lookup.</p>
<pre>function available($domain){
$domain = trim($domain);
if (eregi('^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$',$domain) != 1){
$error = 'Invalid domain (Letters, numbers and hypens only) ('.$domain.')';
return false;
}
preg_match('@^(http://www\.|http://|www\.)?([^/]+)@i', $domain, $preg_metch_result);
$f_result = '';
$domain = $preg_metch_result[2];
$domain_name_array = explode('.', $domain);
$domain_domain = strtolower(trim($domain_name_array[count($domain_name_array)-1]));
$ext_in_list = false;

if (array_key_exists('.'.$domain_domain, $this-&gt;ext)){
$ext_in_list = true;
}

if(strlen($domain) &gt; 0 &amp;&amp; $ext_in_list){
$server = '';

$server = $this-&gt;ext['.' .$domain_domain][0];
$lookup_result = gethostbyname($server);

if ($lookup_result == $server){
$error = 'Error: Invalid extension - '.$domain_domain.'. / server has outgoing connections blocked to '.$server.'.';
return false;
}

$fs = fsockopen($server, 43,$errno,$errstr,10);
if (!$fs || ($errstr != "")){
$error = 'Error: ('.$server.') '.$errstr.' ('.$errno.')';
return false;
}

fputs($fs, "$domain\r\n");
while( !feof($fs) ) {
$f_result .= fgets($fs,128);
}

fclose($fs);

if($domain_domain == 'org'){
nl2br($f_result);
}

if(eregi($this-&gt;ext['.'.$domain_domain][1], $f_result)){
return true;
} else {
return false;
}

} else {
$error = 'Invalid Domain and/or TLD server entry does not exist';
}
return false;
}</pre>
<h2>Going through the method</h2>
<p>I will explain each piece of this method in case you would like to know exactly what is going on.</p>
<pre>  $domain = trim($domain);
if (eregi('^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$',$domain) != 1){
$error = 'Invalid domain (Letters, numbers and hypens only) ('.$domain.')';
return false;
}</pre>
<p>Here we are trimming excess whitespace from the domain, and checking to make sure that it conforms to standards. (Checking if the domain is in a valid format). If it is invalid, we give an error, and return false.</p>
<pre>  preg_match('@^(http://www\.|http://|www\.)?([^/]+)@i', $domain, $preg_metch_result);
$f_result = '';
$domain = $preg_metch_result[2];
$domain_name_array = explode('.', $domain);
$domain_domain = strtolower(trim($domain_name_array[count($domain_name_array)-1]));
$ext_in_list = false;

if (array_key_exists('.'.$domain_domain, $this-&gt;ext)){
$ext_in_list = true;
}</pre>
<p>In this block of code, we are splitting the domain name into it&#8217;s respective parts (domain, extension) and checking to see that the extension (TLD) is in the list that we defined earlier. We set a variable &#8220;$ext_in_list&#8221; to true if it is.</p>
<pre>  if(strlen($domain) &gt; 0 &amp;&amp; $ext_in_list){</pre>
<p>We make sure that the extension is in the list, and the domain is at least 1 character long.</p>
<pre>  $server = '';
$server = $this-&gt;ext['.' .$domain_domain][0];
$lookup_result = gethostbyname($server);

if ($lookup_result == $server){
$error = 'Error: Invalid extension - '.$domain_domain.'. / server has outgoing connections blocked to '.$server.'.';
return false;
}</pre>
<p>In this block of code, we get the corresponding WHOIS server from our predefined list, and get the IP address associated with that server. If the result of the IP lookup is false, we assume that the server is blocking our connection or that the extension is invalid. If not, we assume the lookup was successful and valid.</p>
<pre>  $fs = fsockopen($server, 43,$errno,$errstr,10);
if (!$fs || ($errstr != "")){
$error = 'Error: ('.$server.') '.$errstr.' ('.$errno.')';
return false;
}

fputs($fs, "$domain\r\n");
while( !feof($fs) ) {
$f_result .= fgets($fs,128);
}

fclose($fs);

if($domain_domain == 'org'){
nl2br($f_result);
}</pre>
<p>Here we open a new socket connection on port 43. If the connection fails, we handle the error, and return the method false. If it succeeds, we continue to retrieve result from the socket connection. Once the result is retrieve, we close the connection, and preform some formatting on the results should the domain name be a &#8220;.org&#8221;.</p>
<pre>  if(eregi($this-&gt;ext['.'.$domain_domain][1], $f_result)){
return true;
} else {
return false;
}

} else {
$error = 'Invalid Domain and/or TLD server entry does not exist';
}
return false;
}</pre>
<p>The last block of code will check our extension array defined earlier to see if the result matches the text provided for that specified extension. If the there is a match, we return true, otherwise, we return false.</p>
<h2>Putting it all together</h2>
<p>Now that we know how the class and method works, lets put it all together, and give an example on how to use it in your script.</p>
<pre>class whois {

public $ext = array(
'.com' =&gt; array('whois.crsnic.net','No match for'),
'.net' =&gt; array('whois.crsnic.net','No match for'),
'.org' =&gt; array('whois.publicinterestregistry.net','NOT FOUND'),
'.us' =&gt; array('whois.nic.us','Not Found'),
'.biz' =&gt; array('whois.biz','Not found'),
'.info' =&gt; array('whois.afilias.net','NOT FOUND'),
'.eu' =&gt; array('whois.eurid.eu','FREE'),
'.mobi' =&gt; array('whois.dotmobiregistry.net', 'NOT FOUND'),
'.tv' =&gt; array('whois.nic.tv', 'No match for'),
'.in' =&gt; array('whois.inregistry.net', 'NOT FOUND'),
'.co.uk' =&gt; array('whois.nic.uk','No match'),
'.co.ug' =&gt; array('wawa.eahd.or.ug','No entries found'),
'.or.ug' =&gt; array('wawa.eahd.or.ug','No entries found'),
'.sg' =&gt; array('whois.nic.net.sg','NOMATCH'),
'.com.sg' =&gt; array('whois.nic.net.sg','NOMATCH'),
'.per.sg' =&gt; array('whois.nic.net.sg','NOMATCH'),
'.org.sg' =&gt; array('whois.nic.net.sg','NOMATCH'),
'.com.my' =&gt; array('whois.mynic.net.my','does not Exist in database'),
'.net.my' =&gt; array('whois.mynic.net.my','does not Exist in database'),
'.org.my' =&gt; array('whois.mynic.net.my','does not Exist in database'),
'.edu.my' =&gt; array('whois.mynic.net.my','does not Exist in database'),
'.my' =&gt; array('whois.mynic.net.my','does not Exist in database'),
'.nl' =&gt; array('whois.domain-registry.nl','not a registered domain'),
'.ro' =&gt; array('whois.rotld.ro','No entries found for the selected'),
'.com.au' =&gt; array('whois.ausregistry.net.au','No data Found'),
'.ca' =&gt; array('whois.cira.ca', 'AVAIL'),
'.org.uk' =&gt; array('whois.nic.uk','No match'),
'.name' =&gt; array('whois.nic.name','No match'),
'.ac.ug' =&gt; array('wawa.eahd.or.ug','No entries found'),
'.ne.ug' =&gt; array('wawa.eahd.or.ug','No entries found'),
'.sc.ug' =&gt; array('wawa.eahd.or.ug','No entries found'),
'.ws' =&gt; array('whois.website.ws','No Match'),
'.be' =&gt; array('whois.ripe.net','No entries'),
'.com.cn' =&gt; array('whois.cnnic.cn','no matching record'),
'.net.cn' =&gt; array('whois.cnnic.cn','no matching record'),
'.org.cn' =&gt; array('whois.cnnic.cn','no matching record'),
'.no' =&gt; array('whois.norid.no','no matches'),
'.se' =&gt; array('whois.nic-se.se','No data found'),
'.nu' =&gt; array('whois.nic.nu','NO MATCH for'),
'.com.tw' =&gt; array('whois.twnic.net','No such Domain Name'),
'.net.tw' =&gt; array('whois.twnic.net','No such Domain Name'),
'.org.tw' =&gt; array('whois.twnic.net','No such Domain Name'),
'.cc' =&gt; array('whois.nic.cc','No match'),
'.nl' =&gt; array('whois.domain-registry.nl','is free'),
'.pl' =&gt; array('whois.dns.pl','No information about'),
'.pt' =&gt; array('whois.dns.pt','No match')
);

public $error;

function available($domain){
$domain = trim($domain);
if (eregi('^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$',$domain) != 1){
$error = 'Invalid domain (Letters, numbers and hypens only) ('.$domain.')';
return false;
}
preg_match('@^(http://www\.|http://|www\.)?([^/]+)@i', $domain, $preg_metch_result);
$f_result = '';
$domain = $preg_metch_result[2];
$domain_name_array = explode('.', $domain);
$domain_domain = strtolower(trim($domain_name_array[count($domain_name_array)-1]));
$ext_in_list = false;

if (array_key_exists('.'.$domain_domain, $this-&gt;ext)){
$ext_in_list = true;
}

if(strlen($domain) &gt; 0 &amp;&amp; $ext_in_list){
$server = '';
$server = $this-&gt;ext['.' .$domain_domain][0];
$lookup_result = gethostbyname($server);

if ($lookup_result == $server){
$error = 'Error: Invalid extension - '.$domain_domain.'. / server has outgoing connections blocked to '.$server.'.';
return false;
}

$fs = fsockopen($server, 43,$errno,$errstr,10);

if (!$fs || ($errstr != "")){
$error = 'Error: ('.$server.') '.$errstr.' ('.$errno.')';
return false;
}

fputs($fs, "$domain\r\n");
while( !feof($fs) ) {
$f_result .= fgets($fs,128);
}

fclose($fs);

if($domain_domain == 'org'){
nl2br($f_result);
}

if(eregi($this-&gt;ext['.'.$domain_domain][1], $f_result)){
return true;
} else {
return false;
}

} else {
$error = 'Invalid Domain and/or TLD server entry does not exist';
}
return false;
}

}</pre>
<h2>Using the Domain Availability class</h2>
<p>The use of this class is very straight forward. We first initialize a new instance of our WHOIS class, and then pass the domain name through our availability method.</p>
<pre>$domain = 'soaptray.com';

$whois = new whois;
$result = $whois-&gt;available($domain);

switch($result){
case true: echo 'Domain is available'; break;
case false: echo 'Domain is already registered'; break;
}</pre>
<p>There you have it! Let me know if you find a good use for this class in one of your projects! Good luck and happy coding.</p>
<h2>Download this class</h2>
<p>The working PHP file for this article can be <a href="http://www.soaptray.com/wp-content/uploads/2008/08/soaptraycom-whois_class.zip">downloaded here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.soaptray.com/blog/2008/08/php-domain-availability-lookup/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Filtering User Input in PHP</title>
		<link>http://www.soaptray.com/blog/2008/04/filtering-user-input-in-php/</link>
		<comments>http://www.soaptray.com/blog/2008/04/filtering-user-input-in-php/#comments</comments>
		<pubDate>Fri, 11 Apr 2008 07:44:05 +0000</pubDate>
		<dc:creator>Regan Johnson</dc:creator>
		
		<category><![CDATA[PHP &amp; MySQL]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Tutorials]]></category>

		<category><![CDATA[classes]]></category>

		<category><![CDATA[filter]]></category>

		<category><![CDATA[object oriented programming]]></category>

		<category><![CDATA[oop]]></category>

		<category><![CDATA[php]]></category>

		<category><![CDATA[security]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.soaptray.com/?p=11</guid>
		<description><![CDATA[Never trust input. I have said this many times before, and am always cognizant of this phrase when I am developing new websites or web applications. Always assume that someone is going to try to exploit your program - be it with malicious intentions or not.]]></description>
			<content:encoded><![CDATA[<p>With this article, I want to shed some light on some of the ways to protect the security, quality and integrity of you web applications written in <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> and MySQL. There is always going to be rotten people out there that want to take advantage of a poorly secured or filtered program - think of it <strong>like someone breaking into a house that has no locks on the front door</strong>.</p>
<h2>What is XSS or Cross-site Scripting?</h2>
<p><abbr title="Cross-site Scripting">XSS</abbr> is a method in which malicious users can inject client side scripts into web applications to gain information, bypass user authentication controls and other such things. This is a vulnerability that I see too often because people are trusting user input data - this is something that can be easily avoided using some simple filtering steps.</p>
<h2>Filtering incoming data</h2>
<p>There are many aspects of filtering - or sanitizing - that you must consider when accepting user generated input (think forms, profiles, contact us). For the purpose of this article, I will be placing the individual filters as methods of a class, that is loaded only when we need to deal with filtering data. This method of doing things is efficient, and uses OOP or Object Oriented Programming techniques (another article on that one later!).</p>
<h2>Building the filter class</h2>
<p>I have chosen to use a custom filter class, rather then available extensions, simply because I like to tune each class for the project I am working with - this reduces the amount of code that is being loaded and used.</p>
<p>Using a class may be new to some programmers, but let me assure you that it is well worth it in the end for a number of reasons (mainly scalability, code re-use and ease of changes/updates). A class is comprised of many different methods (which act very similar to functions). I will write another article on classes, but for some more information on the basics of classes, you can take a look at the php.net <a href="http://www.php.net/manual/en/language.oop5.basic.php" title="Learn about Classes and Objects" rel="external nofollow">introduction to classes and objects</a>.</p>
<p>First, let&#8217;s start by building a basic class as an include that we will load when needed. Let&#8217;s name this file [ <strong>class-filter.php</strong> ]</p>
<h4>class-filter.php</h4>
<pre>
&lt;?php

class filter {

}

?&gt;
</pre>
<p>Now that we have our class defined, let&#8217;s add some methods (functions) to it to filter various types of information.</p>
<h4>class-filter.php (continued)</h4>
<pre>
&lt;?php

class filter {

	// Removes all whitespace from a string, including whitespace that isn't trailing or leading
	public function whitespace($str){
		retrun preg_replace('/\s\s+/',' ', $str);
	}

	// Removes characters not valid in an e-mail address
	public function email($email){
		return strtolower(preg_replace('/[^a-z0-9+_.@-]/i','',$email));
	}

	// Removes tags, whitespace
	public function text($str){
		// Ensure it's a string
		$str = strval($str);
		// We strip all html tags
		$str = strip_tags($str);
		// Remove any whitespace using
		// the define method above
		$str = $this->whitespace($str);
		return $str;
	}

}

?&gt;
</pre>
<p>This list can go on for a while, and get quite specific depending on what type of information you wish to filter. I use a much more complicated version in many of my projects that include e-mail validation, verification and more (I would be happy to share some of these with anyone interested - just drop me a comment).</p>
<p>I encourage you all to add project specific methods (functions) to your filter class.</p>
<p>Now that we have our filter class ready, let&#8217;s open up our main project file [ <strong>index.php</strong> ] and include our class file, then initiate the class into an object that we can use to filter data.</p>
<h4>index.php</h4>
<pre>
&lt;?php

// We first include our class
include 'class-filter.php';

// And then we initiate the class (filter) as an object ($filter)
$filter = new filter();

?&gt;
</pre>
<p>That&#8217;s it, we are now ready to start filtering data! Let&#8217;s say that we have a form posting to [ <strong>index.php</strong> ] with several different user values - take a look at the blow example to show you how to filter them.</p>
<h4>index.php (continued)</h4>
<pre>
&lt;?php

// We first include our class
include 'class-filter.php';

// And then we initiate the class (filter) as an object ($filter)
$filter = new filter();

// Let's say they are posting the following from a form:
// $_POST['name'] = 'Regan Johnson&lt;? die("Muahaha"); ?&gt;';
// $_POST['age'] = "23.554";
// $_POST['email'] = 'random spaces %%+symbols@ domain.com';

$name = $filter->text($_POST['name']);
$age = intval($_POST['age']);
$email = $filter->email($_POST['email']);

echo "Hello, my name is $name.";
echo "I am $age years old.";
echo "My e-mail address is $email.";

// Hello, my name is Regan Johnson.
// I am 23 years old.
// My e-mail address is randomspaces+symbols@domain.com.

?&gt;
</pre>
<p>From the above example, you can see that the data is filtered from potentially malicious scripts (<abbr title="Cross-site Scripting">XSS</abbr>) breaking data to harmless data that is expected by (and works with) your program.</p>
<p>Now that the data is not harmful, the next step is to check for errors. An example of error checking for an e-mail address can be seen in my previous article,<br />
<a href="http://www.soaptray.com/2008/04/validate-email-addresses-using-php/" title="Validate e-mail addresses using PHP and DNS" rel="me">Validate e-mail addresses using PHP and DNS</a>.</p>
<p>Finally, you will want to enter the data into your database, or use it as you would like in your web application. I will be completing an article soon on MySQL security, and simple ways to prevent what is known as a MySQL Injection Attack - I will link it here when it&#8217;s finished.</p>
<p>Thanks for reading my article about filtering forms and incoming data in PHP. <strong>I would love to hear some methods that you use in your filtering process</strong> - please leave a comment below. As always, if you enjoy my articles please subscribe to my <a href="http://www.soaptray.com/feed/" rel="me nofollow">RSS Feed</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.soaptray.com/blog/2008/04/filtering-user-input-in-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Validate e-mail addresses using PHP</title>
		<link>http://www.soaptray.com/blog/2008/04/validate-email-addresses-using-php/</link>
		<comments>http://www.soaptray.com/blog/2008/04/validate-email-addresses-using-php/#comments</comments>
		<pubDate>Tue, 08 Apr 2008 09:49:06 +0000</pubDate>
		<dc:creator>Regan Johnson</dc:creator>
		
		<category><![CDATA[PHP &amp; MySQL]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Tutorials]]></category>

		<category><![CDATA[dns]]></category>

		<category><![CDATA[email]]></category>

		<category><![CDATA[mx records]]></category>

		<category><![CDATA[mysql]]></category>

		<category><![CDATA[php]]></category>

		<category><![CDATA[spammers]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[validate]]></category>

		<guid isPermaLink="false">http://www.soaptray.com/?p=9</guid>
		<description><![CDATA[As a PHP programmer, there are a lot of people in this world that piss me off - collectively I label them as spammers! About.com estimates there are 183 billion e-mails sent every day in the world, with over 70% being considered spam - Hell, no wonder why my internet bill is getting to be [...]]]></description>
			<content:encoded><![CDATA[<p>As a PHP programmer, there are a lot of people in this world that piss me off - collectively I label them as spammers! <a title="About.com | E-mail" rel="nofollow" href="http://email.about.com/od/emailtrivia/f/emails_per_day.htm" target="_blank">About.com</a> estimates <strong>there are 183 billion e-mails sent every day in the world</strong>, with <strong>over 70% being considered spam</strong> - Hell, no wonder why my internet bill is getting to be so expensive!</p>
<p>When building new scripts or applications, I am always looking for new ways to increase security and the quality of my user generated content (such as member profiles, posts, comments, etc). There is nothing more frustrating than having an excellent web application that is littered with spam.</p>
<h2>The process I use to determine if an e-mail address is legitimate</h2>
<p>There are a few steps in the process that I use to validate an e-mail address which, together, are built for speed and accuracy. I encourage you to decide which steps you would like to use in your script, as they can also be used separate from each other.</p>
<p>Before we get started, I wanted to note that these functions are not intended to be comprehensive, as we are only checking the domain for MX records, and not the individual e-mail on that domain (which is a bit more complicated then the intentions of this tutorial). With that being said these functions will help narrow down the verification process significantly!</p>
<h2>Filter improperly formatted e-mail addresses</h2>
<p>This step is a good, quick brush to make sure that the e-mail address is in the proper format. I recommend including this step at a minimum - using PHP&#8217;s built in <abbr title="Regular Expression">RegEx</abbr> function, <a title="Learn more about the preg_match function on the PHP.net website" rel="nofollow" href="http://www.php.net/preg_match" target="_blank">preg_match</a>.</p>
<h4>The function</h4>
<pre>
function verify_email($email){

    if(!preg_match('/^[_A-z0-9-]+((\.|\+)[_A-z0-9-]+)*@[A-z0-9-]+(\.[A-z0-9-]+)*(\.[A-z]{2,4})$/',$email)){
        return false;
    } else {
        return $email;
    }
}
</pre>
<p>Because this article is not about regular expression, I am only going to provide a brief explanation about what&#8217;s going on here. Basically, you would call this function (example below) passing in an e-mail address whose format you wish to validate. The regular expression checks that the proper parts of an e-mail address are in the correct places, contain the correct characters, and are the correct lengths - if the e-mail is not formatted correctly, it will return false.</p>
<h4>How to use it</h4>
<pre>
$email = 'test@domain.com';

if(verify_email($email)){
    echo 'Success - E-mail address appears to be valid';
} else {
    echo 'Error - E-mail address appears to be invalid';
}

// sdasda@asdasd.com - true
// asdasd$%@.faa.ca.ds - false
</pre>
<p>While this function will flag some blatant examples of spam, you will notice that some pretty spammy looking e-mails will make it past this step which isn&#8217;t all that great But don&#8217;t worry, we actually test the domain in the following step.</p>
<h2>Check the DNS of the e-mail&#8217;s domain to make sure it has a proper MX Record</h2>
<p>For those of you who don&#8217;t know, and <abbr title="Mail Exchange">MX</abbr> Record is a piece of data on a domain name that tells other computers and servers what to do when someone sends an e-mail address to that domain. By checking to see if an MX Record exists using PHP, we are taking the e-mail verification one step farther - a check that the domain actually exists and it&#8217;s able to host e-mail boxes. We will accomplish this using another one of PHP&#8217;s built in functions, <a title="Learn more about the checkdnsrr function on the PHP.net website" href="http://www.php.net/checkdnsrr" target="_blank" rel="nofollow">checkdnsrr</a>.</p>
<h4>The function</h4>
<pre>
function verify_email_dns($email){

    // This will split the email into its front
    // and back (the domain) portions
    list($name, $domain) = split('@',$email);

    if(!checkdnsrr($domain,'MX')){

        // No MX record found
        return false;

    } else {

        // MX record found, return email
        return $email;

    }
}
</pre>
<p>When using this function, PHP will send a call to the domain of the e-mail address you are attempting to validate, and check its MX records. If they are present and valid, it will return true, otherwise it will return false - simple as that!</p>
<h4>How to use it</h4>
<pre>
$email = 'test@domain.com';

if(verify_email_dns($email)){
    echo 'Success - E-mail has a valid MX record';
} else {
    echo 'Error - E-mail does not have an MX record';
}

// omg@omgomgomgeh.com - false
// steve@apple.com - true
</pre>
<h2>Putting it all together</h2>
<p>Now that we have our functions, and some working examples, let&#8217;s put it all together to be one badass e-mail validation function.</p>
<h4>Example</h4>
<pre>
$email = 'test@domain.com';

if(verify_email($email)){

    // E-mail address looks to be in the proper format
    // lets check the MX records

    if(verify_email_dns($email)){

        // E-mail passed both checks
        echo 'Success - E-mail address appears to be valid.';

    } else {

        // E-mail is invalid, no MC record
        echo 'Error - E-mail domain does not have an MX record.';

    }

} else {

    // E-mail inst formatted correctly
    // so we don't even check its MX record
    echo 'Error - E-mail address appears to be invalid.';

}

// Our function to filter our bogus formatted addresses
function verify_email($email){

    if(!preg_match('/^[_A-z0-9-]+((\.|\+)[_A-z0-9-]+)*@[A-z0-9-]+(\.[A-z0-9-]+)*(\.[A-z]{2,4})$/',$email)){
        return false;
    } else {
        return $email;
    }
}

// Our function to verify the MX records
function verify_email_dns($email){

    // This will split the email into its front
    // and back (the domain) portions
    list($name, $domain) = split('@',$email);

    if(!checkdnsrr($domain,'MX')){

        // No MX record found
        return false;

    } else {

        // MX record found, return email
        return $email;

    }
}
</pre>
<p>There you have it folks! A nifty little function to help keep your user base clean, and spam free! It&#8217;s important to note that the lookup of a domain names MX Record in this manner is currently only supported on Unix based systems - Sorry Windows.</p>
<h3>Extend it into your own projects</h3>
<p>This post is a start to integrating and building these functions into your own projects. For example, On some personal projects, I have taken these functions even farther. Because the MX Record checks takes a second or two to complete, I developed a system to cache results that come back as positive in a database for quick access of common domain names.</p>
<p>Have fun experimenting! As always, if you have any questions, I would love to hear them, and will do my best to help you out!</p>
<h3>Update</h3>
<p>I changed the verify_email() function above to use <strong>preg_match</strong> instead of <strong>eregi</strong> for the regular expression. This method is much faster. Someone pointed out to me that the regex was not updated for allowing &#8220;+&#8221; within the address, something that is starting to catch on. I have made the changes, and tested things out. Thanks for pointing this out to me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.soaptray.com/blog/2008/04/validate-email-addresses-using-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A new blog is born</title>
		<link>http://www.soaptray.com/blog/2008/04/a-new-blog-is-born/</link>
		<comments>http://www.soaptray.com/blog/2008/04/a-new-blog-is-born/#comments</comments>
		<pubDate>Tue, 01 Apr 2008 21:16:03 +0000</pubDate>
		<dc:creator>Regan Johnson</dc:creator>
		
		<category><![CDATA[Personal]]></category>

		<category><![CDATA[about me]]></category>

		<category><![CDATA[introduction]]></category>

		<category><![CDATA[welcome]]></category>

		<guid isPermaLink="false">http://www.soaptray.com/wordpress/?p=7</guid>
		<description><![CDATA[A quick introduction for this blog, and Regan Johnson, the creative mogul behind Soaptray. I hope to use this blog to share some of the neat things I come across while designing and developing websites.]]></description>
			<content:encoded><![CDATA[<p>Well, it&#8217;s been a long time coming, but my blog is finally here. In between working full time on my latest venture, <a title="Datepad is a free online dating site" href="http://www.datepad.com" target="_blank">Datepad</a>, spending time with my family, and trying to get outside more, I&#8217;ve managed to <span style="text-decoration: line-through;">slave </span>squeeze some time in to get my blog off the ground.</p>
<h2>Let me introduce myself, so that we are no longer strangers.</h2>
<p>My name is Regan Johnson - a 22 year old bloke from Calgary, Alberta, Canada - it&#8217;s nice to meet you! I&#8217;m a creative web developer with a savvy blend of skills within my profession - a mix which is unique - programming, design &amp; marketing.</p>
<p>My mentor taught me much of what I know today, and I owe many of my successes in this industry to him. Because of his selflessness, and the effect it has had on me, I feel compelled to share what I know with others in hopes of returning the favor. If your interested, <a title="Learn about Regan Johnson" href="http://www.soaptray.com/about/" target="_self">learn more about me</a>.</p>
<h2>I bet a lot of you are wondering what a crazy name like &#8220;soaptray&#8221; means.</h2>
<p>The name is something catchy, unique, and easy to brand. Soaptray Inc. is the name of my creative design studio here in Calgary. I have a handful of excellent clients, and I love my job (if you can even call it that). Soaptray is also a place to share and organize my ideas. Since you are reading this post, I don&#8217;t think it needs any more introduction.</p>
<p>Thanks for checking out my new home on the net, and I look forward to meeting some great people along the way. Why not introduce yourself and <a title="Leave me a comment" href="http://www.soaptray.com/2008/04/a-new-blog-is-born/#comments">leave me a comment</a> below?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.soaptray.com/blog/2008/04/a-new-blog-is-born/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
