lukey
lukey

Reputation: 29

creating a username that is an emailaddress

I have a login for my site. Below shows the registration page. The emailaddress is their username. How do create an error message alert if an @ symbol and . has not been inserted into the username(emailaddress) field?

<?php

// Check if he wants to register:
if (!empty($_POST[emailaddress]))
{
    // Check if passwords match.
    if ($_POST[password] != $_POST[password2])
        exit("Error - Passwords don't match. Please go back and try again.");

    // Assign some variables.
    $date = mktime("d - m - Y");
    $ip = $_SERVER[REMOTE_ADDR];

    require_once("config.php");

    // Register him.
    $query = mysql_query("INSERT INTO neworders 
    (emailaddress, firstname, surname, password, datereg, ip)
    VALUES  ('$_POST[emailaddress]','$_POST[firstname]','$_POST[surname]','$_POST[password]','$datereg','$ip')")
    or die ("Error - Couldn't register user.");

    echo "Welcome $_POST[username]! You've been successfully reigstered!<br /><br />
        Please login <a href='login.php'><b>here</b></a>.";
    exit();
}

?>

Upvotes: 0

Views: 103

Answers (3)

Adi Gandra
Adi Gandra

Reputation: 661

You can check if a string has characters in it with the stristr() php function (This is not the ideal solution, but just very simply checks if characters in a string exist like you described. Using filter_var as described below is a better solution). So to do what you are asking you could do something like:

if(!(stristr($_POST['emailaddress'], '@') && stristr($_POST['emailaddress'], '.')) {
  echo 'Email not valid';
  exit(1);
}

Something else you could do is use the prebuilt php filter_var function to do this: http://php.net/manual/en/function.filter-var.php

if(!filter_var($_POST['emailaddress'],FILTER_VALIDATE_EMAIL)) {
  echo 'Email not valid';
  exit(1);
}

You can also use regex pattern matching if you want. I would also advise to do some sort of cleaning (mysql_real_string_escape) on the $_POST['emailaddress'] field, if you are inserting it into a database.

Upvotes: 0

alex
alex

Reputation: 490253

You should probably use a more robust solution to validate emails. Use PHP's filter_var() function with the FILTER_VALIDATE_EMAIL flag.

$validEmail = filter_var($email, FILTER_VALIDATE_EMAIL);

Of course, this is just for validating the email. If you're inserting it into a database, use that database's escape mechanism for strings or use bound queries.

Upvotes: 2

Marty Cortez
Marty Cortez

Reputation: 2343

Use the function at the bottom of this page:

http://www.linuxjournal.com/article/9585

Upvotes: 0

Related Questions