Jump to content

[SOLVED] Problems With Email Validation


Akenatehm

Recommended Posts

Hey Guys,

 

I am working on a small User Management System. It currently validates usernames and checks that passwords match. It is mostly practice for me with OOP PHP.

 

I am trying to get this to validate email also but the page changes and then goes blank once you click on Submit.

 

Here's the Class:

<?php

class Register{
private $dbhost,$dbuser,$dbpass,$database,$LastResult;
public function __construct($dbhost,$dbuser,$dbpass,$database) {
       $this->dbhost = $dbhost;
        $this->dbuser = $dbuser;
        $this->dbpass = $dbpass;
        $this->database = $database;
   	}
public function checkUsername($username){
	$this->username = mysql_escape_string($username);
	$connect = mysql_connect($this->dbhost,$this->dbuser,$this->dbpass) or die(mysql_error());
	mysql_select_db($this->database) or die(mysql_error());	
	$checkuser= mysql_query("SELECT * FROM users WHERE Username = '$this->username'") or die(mysql_error());
	if(mysql_num_rows($checkuser) == 1){
		$response = "Username Already Exists <br />";
	}
echo $response;
mysql_close($connect);
}

public function samePasswords($password,$confirmpassword){
	$this->password = md5(mysql_escape_string($password));
	$this->confirmpassword = md5(mysql_escape_string($confirmpassword));
	if($this->password != $this->confirmpassword){
		$response = "Passwords Do Not Match<br />";	
	}	
	echo $response;
	}

/**
Validate an email address.
Provide email address (raw input)
Returns true if the email address has the email 
address format and the domain exists.
*/
public function checkEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || 
↪checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   
   return $isValid;
}
   


public function createUser($username,$password,$email){
$connect = mysql_connect($this->dbhost,$this->dbuser,$this->dbpass) or die(mysql_error());
mysql_select_db($this->database) or die(mysql_error());	
$insertuser = mysql_query("INSERT into users (username,password,email) values('$username','$password','$email')") or die(mysql_error());
if($insertuser){
	echo "<h1>Success</h1>";
    	echo "<p>Your account was successfully created. Please <a href=\"index.php\">click here to login</a>.</p>";
}

elseif(!$insertuser){
     	echo "<h1>Error</h1>";
        echo "<p>Sorry, your registration failed. Please go back and try again.</p>"; 	
}
mysql_close($connect);



}



}
?>

 

and the Registration Page:

<?php
session_start();
require "Connection.class.php";
require 'Member.class.php';
$select = new Connection('localhost','root','');
$select->db ('TimelessVoice');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<title>User Management System (Tom Cameron for NetTuts)</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
<script src="jquery.js" type="text/javascript"></script>
<script src="validate/cmxforms.js" type="text/javascript"></script>
<script type="text/javascript" src="validate/jquery.validate.js"></script>
<script type="text/javascript">
$().ready(function() {
// validate signup form on keyup and submit
$("#registerform").validate({
	rules: {
		username: {
			required: true,
			minlength: 5
		},
		password: {
			required: true,
			minlength: 5
		},
		confirmpassword: {
			required: true,
			minlength: 5,
			equalTo: "#password"
		},
		email: {
			required: true,
			email: true
		},

	messages: {
		username: {
			required: "Please enter a username",
			minlength: "Your username must consist of at least 5 characters"
		},
		password: {
			required: "Please provide a password",
			minlength: "Your password must be at least 5 characters long"
		},
		confirm_password: {
			required: "Please provide a password",
			minlength: "Your password must be at least 5 characters long",
			equalTo: "Please enter the same password as above"
		},
		email: "Please enter a valid email address"
	}
	}		
});
	});
// check if confirm password is still valid after password changed
$("#password").blur(function() {
	$("#confirmpassword").valid();


	});

</script> 
</head>  
<body>  
<div id="main">
<?php

if(!empty($_POST['username']) && !empty($_POST['password']))
{
    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = '';
    $database = 'TimelessVoice';
    $servervalidation = new Register($dbhost,$dbuser,$dbpass,$database);
$servervalidation->checkUsername($_POST['username']);
$servervalidation->samePasswords($_POST['password'],$_POST['confirmpassword']);

if($servervalidation->CheckEmail($_POST['email'])){
$servervalidation->createUser($servervalidation->username,$servervalidation->password,$servervalidation->email);
}
}
else{
?>
    
   <h1>Register</h1>
    
   <p>Please enter your details below to register.</p>
    
<form method="post" action="register.php" name="registerform" id="registerform" class="cmxform">
<fieldset>
	<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
	<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
	<label for="confirmpassword">Confirm Password:</label><input type="password" name="confirmpassword" id="confirmpassword" /><br />
        <label for="email">Email Address:</label><input type="text" name="email" id="email" /><br />
	<input type="submit" name="register" id="register" value="Register" />
</fieldset>
</form>
    
   <?php
}
?>
</div>
</body>
</html>

 

Help would be greatly appreciated and suggestions will be warmly accepted.

 

Regards,

Cody

Link to comment
Share on other sites

A part of my coding

 

register.php


    $name = $first . ' ' . $surname;
    $actkey = mt_rand(1, 500) . 'f78dj899dd';
    $act = sha1($actkey);

    $query = mysql_query("INSERT INTO Users (Username, Password, Name, Email, Date, IP, Actkey) VALUES ('$username','$password','$name','$email','$date','$ip','$act')") or
        die(mysql_error());
    $send = mail($email, "Registration Confirmation",
        "Thank you for registering with AvDose\n\nYour username and password is below, along with details on how to activate your account.\n\nUser: " .
        $username . "\nPass: " . $pass . "\n\nClick the link below to activate your account:\nhttp://avateinfo.kh3.us/activate.php?id=" .
        $act . "\n\nPlease do not reply, this is an automated mailer.\n\nThanks",
        "FROM: noreply@avateinfo.kh3.us");

    if (($query) && ($send)) {

 

activate.php

<?php

include 'config.php';

$id = $_GET['id'];

$query = mysql_query("SELECT * FROM Users WHERE Actkey = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_array($query);

if(mysql_num_rows($query) > 0){

$user = $row['id'];

$do = mysql_query("UPDATE Users SET Activated = 1 WHERE id = '$user' LIMIT 1") or die(mysql_error());
$send = mail($row['Email'] , "Activation Confirmation" , "Thank you for activating your account, you are now fully registered and able to use our services.\n\nTo login, click the link below:\nhttp://avateinfo.kh3.us/members.avt" , "FROM: noreply@avteinfo.kh3.us");

if(($do)&&($send))
{

echo '<link href="style.css" rel="stylesheet" type="text/css">
<div id="success">
<p>Activation successful! A confirmation email has been dispatched. You can now login!</p>
<p><a href="login.php">Click here</a> to goto the login page.</p>
</div>';

} else {

echo '<link href="style.css" rel="stylesheet" type="text/css">
<div id="error">
<p>We are sorry, there appears to be an error processing your activation. Please try again later.</p>
</div>';

}

} else {

echo '<link href="style.css" rel="stylesheet" type="text/css">
<div id="error">
<p>Sorry, your activation code was incorrect. Please try again.</p>
</div>';

}

mysql_close($l);
?>

 

Link to comment
Share on other sites

Here's the email format validation I use:

function is_email($email)
{
    $formatTest = '/^[-\w+]+(\.[-\w+]+)*@[-a-z\d]{2,}(\.[-a-z\d]{2,})*\.[a-z]{2,6}$/i';
    $lengthTest = '/^(.{1,64})@(.{4,255})$/';

    return (preg_match($formatTest, $email) && preg_match($lengthTest, $email));
}
// NOTES:
//
// Format test
// - Username accepts: 'a-z', 'A-Z', '0-9', '_' (underscore), '-' (dash), '+' (plus), & '.' (period)
//       Note: cannot start or end with a period (and connot be in succession)
// - Domain accepts: 'a-z', 'A-Z', '0-9', '-' (dash), & '.' (period)
//       Note: cannot start or end with a period (and connot be in succession)
// - TLD accepts: 'a-z', 'A-Z', & '0-9'
//
// Length test
// - Username: 1 to 64 characters
// - Domain: 4 to 255 character

 

Also, I notice your functions starts out with the assumption the $isValid value is true. When doing validations I think it is better practice to assume it is not valid until proven otherwise.

Link to comment
Share on other sites

WHat does this return? I would rather an If....Else to show a true or false reply.

 

Could you help me with that please?

 

Here's the rest of the comments for the function

//=====================================================
// Function: is_email ( string $email )
//
// Description: Finds whether the given string variable
//              is a properly formatted email.
//
// Parameters: $email the string being evaluated
//
// Return Values: Returns TRUE if $email is valid email
//                format, FALSE otherwise.
//=====================================================

 

The function DOES return a true or false. Why would youwant to use an if/else when it is not needed.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.