HMV.co.in

September 23, 2008

Validate an email address using regular expressions

Filed under: php — Tags: , , , — Harsha M V @ 10:52 pm

Description

If you want a PHP script to verify an email address then use this quick and simple PHP regular expression for email validation. This is also case-insensitive, so it will treat all characters as lower case. It is a really easy way to check the syntax and format of an email address.

The code


<?php

$email "someone@example.com";

if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$"$email)) {

  echo "Valid email address.";

}

else {

  echo "Invalid email address.";

}

?>

September 22, 2008

10 projects every php developer should use

Filed under: tools — Tags: , , , , , , , , , — Harsha M V @ 6:28 pm

As a php web developer, you should know that php is probably the language that has the biggest code repository. So no matter what module you want to include in your project there should be an open source solution.

This can help in various ways, but just in case you can’t think of one, here I put a few :

  • Open source is worked by many people, so the result is for sure better than one man’s work
  • You can have free updates to your code, while otherwise you should code the updates each time something new comes up
  • You save development time while your project is getting better

Anyway, after many years as a web developer, I’ve compiled a list of php classes that can be easily integrated in any project and I am regularly use.

Sending Emails

Sending emails is something very common for every web site. Php’s mail() Visit through proxy function is good for this, but what if you want to attach a file, or send through an SMTP server, etc? Well in that case you should use phpmailer Visit through proxy

User Manipulation

Another common module is the user module. With that you can manipulate users (login, logout, register, etc.) Personally I’ve never found a project that is good enough, so I created my own Smiley

Php user class Visit through proxy is a module that can be used even in established projects, as it uses variable data for database tables, fields, session variables, etc.

Fetching RSS Feeds

Ever wanted to fetch an rss feed from your project? Well there is always an easy way to fetch a feed Visit through proxy but in most cases you need more than that. When that is the case you should definitely use Magpie RSS Visit through proxy

Geotargeting

There are many times that you need to know where are your visitors coming from. Maxmind Visit through proxy gives a solution to this. For a complete tutorial check this article Visit through proxy

Grabbing Remote Content

Some times RSS is not enough so you need to grab the content of a web page and parse it. If you are a huge fun of preg you should not continue reading, but if you are not you definitely need the htmlSQL class Visit through proxy The htmlSQL class allow you to access html values with SQL code. Nice huh? Smiley

Trackback

Sending and receiving trackbacks is vital for a web site in our age. And in fact it is very easy if you are using a class like php trackback Visit through proxy

Template System

Another thing that all sites use is a template. A template engine can save you lots of time, while it can make display changes very easy. A complete template engine that most projects use is Smarty Visit through proxy

BBcode

BBcode used to be a functionality for forums, but as more and more sites use it in order to be more friendly to their users, you might want to use BBcode to your site. The problem is that BBcode requires a lot of coding and I am not sure if you have the time for this. If you don’t you’ll find StringParser_BBcode class Visit through proxy very useful Smiley

Paypal Payment Integration

As you may know paypal has a nice API for developers who want to integrate paypal payments in their sites. The paypal IPN integration class Visit through proxy helps you make use of it and start accepting payments in 20 minutes.

Editor Controls

I don’t have a problem to make changes to a site using phpMyAdmin or a simple text area, but when it comes to my clients I have to give them more than that. A javascript WYSIWYG editor is a perfect solution but as it requires countless hours to get it done I would suggest you to use the tinyMCE control Visit through proxy

Hope you enjoyed this list. If I forgot something feel free to comment above Smiley

8 Practical PHP Regular Expressions

Filed under: php — Tags: , , , , , , — Harsha M V @ 6:11 pm

Here are eight examples of practical PHP regular expressions and techniques that I’ve used over the past few years using Perl Compatible Regular Expressions. This guide goes over the eight different validation techniques and describes briefly how they work. Usernames, telephone numbers, email addresses, and more. Here are eight examples of practical PHP regular expressions and techniques that I’ve used over the past few years using Perl Compatible Regular Expressions. This guide goes over the eight different validation techniques and describes briefly how they work. Usernames, telephone numbers, email addresses, and more.

Validating Usernames

Something often overlooked, but simple to do with a regular expression would be username validation. For example, we may want our usernames to be between 4 and 28 characters in length, alpha-numeric, and allow underscores.

<?php
$string
= "userNaME4234432_";
if (
preg_match('/^[a-z\d_]{4,28}$/i', $string)) {
echo
"example 1 successful.";
}
?>

Validating Telephone Numbers

A much more interesting example would be matching telephone numbers (US/Canada.) We’ll be expecting the number to be in the following form: (###)###-####

<?php
$string
= "(032)555-5555";
if (
preg_match('/^(\(?[2-9]{1}[0-9]{2}\)?|[0-9]{3,3}[-. ]?)[ ][0-9]{3,3}[-. ]?[0-9]{4,4}$/', $string)) {
echo
"example 2 successful.";
}
?>

Thanks to Chris for pointing out that there are no US area codes below 200.

Again, whether the phone number is typed like (###) ###-####, or ###-###-#### it will validate successfully. There is also a little more leeway than specifically checking for enough numbers, because the groups of numbers can have or not have parenthesis, and be separated by a dash, period, or space.

Email Addresses

Another practical example would be an email address. This is fairly straightforward to do. There are three basic portions of an email address, the username, the @ symbol, and the domain name. The following example will check that the email address is in the valid form. We’ll assume a more complicated form of email address, to make sure that it works well with even longer email addresses.

<?php
$string
= "first.last@domain.co.uk";
if (
preg_match(
'/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',
$string)) {
echo
"example 3 successful.";
}
?>

Postal Codes

Validating Postal codes (Zip codes?,) is another practical example, but is a good example to show how ? works in regular expressions.


<?php
$string
= "55324-4324";
if (
preg_match('/^[0-9]{5,5}([- ]?[0-9]{4,4})?$/', $string)) {
echo
"example 4 successful.";
}
?>

What the ? does in this example is saying that the extra 4 digits at the end can either not exist, or exist- but only once. That way, whether or not they type them in, it will still validate correctly.

IP Addresses

Without pinging or making sure it’s actually real, we can make sure that it’s in the right form. We’ll be expecting a normally formed IP address, such as 255.255.255.0.

<?php
$string
= "255.255.255.0";
if (
preg_match(
'^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$',
$string)) {
echo
"example 5 successful.";
}
?>

Hexadecimal Colors

Moving right along with numbers, we could check for Hexadecimal color codes, in short hand or long hand format (#333, 333, #333333 or 333333) with an optional # symbol. This could be useful in a lot of different ways… maybe previewing CSS files? Grabbing colors off pages? The options are endless.

<?php
$string
= "#666666";
if (
preg_match('/^#(?:(?:[a-f\d]{3}){1,2})$/i', $string)) {
echo
"example 6 successful.";
}
?>

Multi-line Comments

- A simple way to find or remove PHP/CSS/Other languages multi-line comments could be useful as well.

<?php
$string
= "/* commmmment */";
if (
preg_match('/^[(/*)+.+(*/)]$/', $string)) {
echo
"example 7 successful.";
}
?>

Dates

- And my last simple, yet practical example would be dates, in my favorite MM/DD/YYYY format.

<?php
$string
= "10/15/2007";
if (
preg_match('/^\d{1,2}\/\d{1,2}\/\d{4}$/', $string)) {
echo
"example 8 successful.";
}
?>

Thanks to Dave Doyle for correcting and improving the username, zip code, IP address, and date regular expressions.

These are just some examples of the Regular Expressions I’ve written to “get the job done” for quite awhile. They work well for the uses in which I’ve needed them, and hopefully they’ll be of some use to you as well.

Have some regular expressions you’re having a problem with? Check out our Guide for PHP Regular Expressions and PCRE Tester and Cheat Sheet. Looking for a regular expression to do something particular? Leave a comment, I’d love to hear what you have to say, and would love to hear some of your ideas for other regular expressions.

Validate e-mail addresses using PHP

Filed under: php — Tags: , , — Harsha M V @ 6:05 pm

<?php
$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;

}
}
?>

some good practices

  1. Use ip2long() and long2ip() to store IP addresses as integers instead of strings in a database. This will reduce the storage space by almost a factor of four (15 bytes for char(15) vs. 4 bytes for the integer), make it easier to calculate whether a certain address falls within a range, and speed-up searches and sorts (sometimes by quite a bit).
  2. Partially validate email addresses by checking that the domain name exists with checkdnsrr(). This built-in function checks to ensure that a specified domain name resolves to an IP address. A simple user-defined function that builds on checkdnsrr() to partially valid email addresses can be found in the user comments section in the PHP docs. This is handy for catching those occasional folks who think their email address is ‘joeuser@wwwphp.net’ instead of ‘joeuser@php.net’.
  3. Automatically print a nicely formatted copy of a page’s source code with highlight_file().This function is handy for when you need to ask for some assistance with a script in a messageboard, IRC, etc. Obviously, some care must be taken not to accidently show your source when it contains DB connection information, passwords, etc.
  4. Prevent potentially sensitive error messages from being shown to users with the error_reporting(0) function. Ideally error reporting should be completely disabled on a production server from within php.ini. However if you’re on a shared webhost and you aren’t given your own php.ini, then your best bet is to add error_reporting(0); as the first line in each of your scripts (or use it with require_once().) This will prevent potentially sensitive SQL queries and path names from being displayed if things go awry.
  5. Use gzcompress() and gzuncompress() to transparently compress/decompress large strings before storing them in a database. These built-in functions use the gzip algorithm and can compress plaintext up to 90%. I use these functions almost everytime I read/write to a BLOB field within PHP. The only exception is when I need full text indexing capabilities.

Blog at WordPress.com.