How to validate an email address with regex in php

Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

How to validate an email address with regex in php

Post by Saman » Wed Jun 16, 2010 5:45 am

Code: Select all

function ValidEmail($email) {
    if(preg_match("/^[a-zA-Z][\w\.-]*[a-zA-Z0-9_]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/",$email)) {
        return 1;
    } else {
        return 0;
    }
} 
Create a Random String
Create a random string of $size digits. Useful for registration codes, etc.

Code: Select all

function randomString($size) {
    // Add any characters you want in your string to this line
    $charset="abcdefghijklmnopqrstuvwyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    $string = "";
    for($i=0; $i < $size; $i++) {
        $string .= $charset[(mt_rand(0,(strlen($charset) -1)))];
    }
    return $string;
} 
Clean the Session ID from the request URI
Sometimes it's necessary to pass the session name and session ID to a script. This is especially useful when redirecting between secure and non-secure pages on the same site. However, it looks bad in the browser, and can be a security concern. This little snippet of code will remove the Session ID by redirecting the user to the same url, but eliminate the session information

Code: Select all

## Cleanup the session id from the url
$_session_name = session_name();
if(isset($_GET[$_session_name])) {
    $_session_id = session_id();
    $new_query_string = preg_replace("/$_session_name=$_session_id/",'',$_SERVER['QUERY_STRING']);
    $redirect = $_SERVER['SCRIPT_URI']."?".$new_query_string;
    header("Location: $redirect");
    exit;
} 
Post Reply

Return to “PHP & MySQL”