Registration form validation not validating
- by jgray
I am a noob when it comes to web development. I am trying to validate a registration form and to me it looks right but it will not validate.. This is what i have so far and i am validating through a repository or database. Any help would be greatly appreciated. thanks
<?php
session_start();
$title = "User Registration";
$keywords = "Name, contact, phone, e-mail, registration";
$description = "user registration becoming a member.";
require "partials/_html_header.php";
//require "partials/_header.php";
require "partials/_menu.php";
require "DataRepository.php";
// if all validation passed save user
$db = new DataRepository();
// form validation goes here
$first_nameErr = $emailErr = $passwordErr = $passwordConfirmErr = "";
$first_name = $last_name = $email = $password = $passwordConfirm = "";
if(isset($_POST['submit']))
{
$valid = TRUE;
// check if all fields are valid
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["first_name"]))
{$first_nameErr = "Name is required";}
else
{
// $first_name = test_input($_POST["first_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$first_name))
{
$first_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
// $email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (!preg_match("/(......)/",$password))
{
$passwordErr = "Subject must contain THREE or more characters!";
}
if ($_POST['password']!= $_POST['passwordConfirm'])
{
echo("Oops! Password did not match! Try again. ");
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
}
if(!$db->isEmailUnique($_POST['email']))
{
$valid = FALSE;
//display errors in the correct places
}
// if still valid save the user
if($valid)
{
$new_user = array(
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'password' => $_POST['password']
);
$results = $db->saveUser($new_user);
if($results == TRUE)
{
header("Location: login.php");
}
else
{
echo "WTF!";
exit;
}
}
}
?>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<h1 class="center"> World Wide Web Creations' User Registration </h1>
<p><span class="error"></span><p>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return validate_form()" >
First Name: <input type="text" name="first_name" id="first_name" value="<?php echo $first_name;?>" />
<span class="error"> <?php echo $first_nameErr;?></span>
<br />
<br />
Last Name(Optional): <input type="text" name="last_name" id="last_name" value="<?php echo $last_name;?>" />
<br />
<br />
E-mail: <input type="email" name="email" id="email" value="<?php echo $email;?>" />
<span class="error"> <?php echo $emailErr;?></span>
<br />
<br />
Password: <input type="password" name="password" id="password" value="" />
<span class="error"> <?php echo $passwordErr;?></span>
<br />
<br />
Confirmation Password: <input type="password" name="passwordConfirm" id="passwordConfirm" value="" />
<span class="error"> <?php echo $passwordConfirmErr;?></span>
<br />
<br />
<br />
<br />
<input type="submit" name="submit" id="submit" value="Submit Data" />
<input type="reset" name="reset" id="reset" value="Reset Form" />
</form>
</body>
</html>
<?php
require "partials/_footer.php";
require "partials/_html_footer.php";
?>
class DataRepository {
// version number
private $version = "1.0.3";
// turn on and off debugging
private static $debug = FALSE;
// flag to (re)initialize db on each call
private static $initialize_db = FALSE;
// insert test data on initialization
private static $load_default_data = TRUE;
const DATAFILE = "203data.txt";
private $data = NULL;
private $errors = array();
private $user_fields = array(
'id' => array('required' => 0),
'created_at' => array('required' => 0),
'updated_at' => array('required' => 0),
'first_name' => array('required' => 1),
'last_name' => array('required' => 0),
'email' => array('required' => 1),
'password' => array('required' => 1),
'level' => array('required' => 0, 'default' => 2),
);
private $post_fields = array(
'id' => array('required' => 0),
'created_at' => array('required' => 0),
'updated_at' => array('required' => 0),
'user_id' => array('required' => 1),
'title' => array('required' => 1),
'message' => array('required' => 1),
'private' => array('required' => 0, 'default' => 0),
);
private $default_user = array(
'id' => 1,
'created_at' => '2013-01-01 00:00:00',
'updated_at' => '2013-01-01 00:00:00',
'first_name' => 'Admin Joe',
'last_name' => 'Tester',
'email' => '[email protected]',
'password' => 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3',
'level' => 1,
);
private $default_post = array(
'id' => 1,
'created_at' => '2013-01-01 00:00:00',
'updated_at' => '2013-01-01 00:00:00',
'user_id' => 1,
'title' => 'My First Post',
'message' => 'This is the message of the first post.',
'private' => 0,
);
// constructor will load existing data into memory
// if it does not exist it will create it and initialize if desired
public function __construct()
{
// check if need to reset
if(DataRepository::$initialize_db AND file_exists(DataRepository::DATAFILE))
{
unlink(DataRepository::DATAFILE);
}
// if file doesn't exist, create the initial datafile
if(!file_exists(DataRepository::DATAFILE))
{
$this->log("Data file does not exist. Attempting to create it... (".__FUNCTION__.":".__LINE__.")");
// create initial file
$this->data = array(
'users' => array(
),
'posts' => array()
);
// load default data if needed
if(DataRepository::$load_default_data)
{
$this->data['users'][1] = $this->default_user;
$this->data['posts'][1] = $this->default_post;
}
$this->writeTheData();
}
// load the data into memory for use
$this->loadTheData();
}
private function showErrors($break = TRUE, $type = NULL)
{
if(count($this->errors) > 0)
{
echo "<div style=\"color:red;font-weight: bold;font-size: 1.3em\":<h3>$type Errors</h3><ol>";
foreach($this->errors AS $error)
{
echo "<li>$error</li>";
}
echo "</ol></div>";
if($break)
{
"</br></br></br>Exiting because of errors!";
exit;
}
}
}
private function writeTheData()
{
$this->log("Attempting to write the datafile: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")");
file_put_contents(DataRepository::DATAFILE, json_encode($this->data));
$this->log("Datafile written: ".DataRepository::DATAFILE." (line: ".__LINE__.")");
}
private function loadTheData()
{
$this->log("Attempting to load the datafile: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")");
$this->data = json_decode(file_get_contents(DataRepository::DATAFILE), true);
$this->log("Datafile loaded: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")", $this->data);
}
private function validateFields(&$info, $fields, $pre_errors = NULL)
{
// merge in any pre_errors
if($pre_errors != NULL)
{
$this->errors = array_merge($this->errors, $pre_errors);
}
// check all required fields
foreach($fields AS $field => $reqs)
{
if(isset($reqs['required']) AND $reqs['required'] == 1)
{
if(!isset($info[$field]) OR strlen($info[$field]) == 0)
{
$this->errors[] = "$field is a REQUIRED field";
}
}
// set any default values if not present
if(isset($reqs['default']) AND (!isset($info[$field]) OR $info[$field] == ""))
{
$info[$field] = $reqs['default'];
}
}
$this->showErrors();
if(count($this->errors) == 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
private function validateUser(&$user_info)
{
// check if the email is already in use
$this->log("About to check pre_errors: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")", $user_info);
$pre_errors = NULL;
if(isset($user_info['email']))
{
if(!$this->isEmailUnique($user_info['email']))
{
$pre_errors = array('The email: '.$user_info['email'].' is already used in our system');
}
}
$this->log("After pre_error check: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")", $pre_errors);
return $this->validateFields($user_info, $this->user_fields, $pre_errors);
}
private function validatePost(&$post_info)
{
// check if the user_id in the post actually exists
$this->log("About to check pre_errors: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")", $post_info);
$pre_errors = NULL;
if(isset($post_info['user_id']))
{
if(!isset($this->data['users'][$post_info['user_id']]))
{
$pre_errors = array('The posts must belong to a valid user. (User '.$post_info['user_id'].' does not exist in the data');
}
}
$this->log("After pre_error check: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")", $pre_errors);
return $this->validateFields($post_info, $this->post_fields, $pre_errors);
}
private function log($message, $data = NULL)
{
$style = "background-color: #F8F8F8;
border: 1px solid #DDDDDD;
border-radius: 3px;
font-size: 13px;
line-height: 19px;
overflow: auto;
padding: 6px 10px;";
if(DataRepository::$debug)
{
if($data != NULL)
{
$dump = "<div style=\"$style\"><pre>".json_encode($data, JSON_PRETTY_PRINT)."</pre></div>";
}
else
{
$dump = NULL;
}
echo "<code><b>Debug:</b> $message</code>$dump<br />";
}
}
public function saveUser($user_info)
{
$this->log("Entering saveUser: (".__FUNCTION__.":".__LINE__.")", $user_info);
$mydata = array();
$update = FALSE;
// check for existing data
if(isset($user_info['id']) AND $this->data['users'][$user_info['id']])
{
$mydata = $this->data['users'][$user_info['id']];
$this->log("Loaded prior user: ".print_r($mydata, TRUE)." (".__FUNCTION__.":".__LINE__.")");
}
// copy over existing values
$this->log("Before copying over existing values: (".__FUNCTION__.":".__LINE__.")", $mydata);
foreach($user_info AS $k => $v)
{
$mydata[$k] = $user_info[$k];
}
$this->log("After copying over existing values: (".__FUNCTION__.":".__LINE__.")", $mydata);
// check required fields
if($this->validateUser($mydata))
{
// hash password if new
if(isset($mydata['password']))
{
$mydata['password'] = sha1($mydata['password']);
}
// if no id, add the next available one
if(!isset($mydata['id']) OR (int)$mydata['id'] < 1)
{
$this->log("No id set: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")");
if(count($this->data['users']) == 0)
{
$mydata['id'] = 1;
$this->log("Setting id to 1: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")");
}
else
{
$mydata['id'] = max(array_keys($this->data['users']))+1;
$this->log("Found max id and added 1 [".$mydata['id']."]: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")");
}
}
// set created date if null
if(!isset($mydata['created_at']))
{
$mydata['created_at'] = date ("Y-m-d H:i:s", time());
}
// update modified time
$mydata['modified_at'] = date ("Y-m-d H:i:s", time());
// copy into data and save
$this->log("Before data save: (".__FUNCTION__.":".__LINE__.")", $this->data);
$this->data['users'][$mydata['id']] = $mydata;
$this->writeTheData();
}
return TRUE;
}
public function getUserById($id)
{
if(isset($this->data['users'][$id]))
{
return $this->data['users'][$id];
}
else
{
return array();
}
}
public function isEmailUnique($email)
{
// find the user that has the right username/password
foreach($this->data['users'] AS $k => $v)
{
$this->log("Checking unique email: {$v['email']} == $email (".__FUNCTION__.":".__LINE__.")", NULL);
if($v['email'] == $email)
{
$this->log("FOUND NOT unique email: {$v['email']} == $email (".__FUNCTION__.":".__LINE__.")", NULL);
return FALSE;
break;
}
}
$this->log("Email IS unique: $email (".__FUNCTION__.":".__LINE__.")", NULL);
return TRUE;
}
public function login($username, $password)
{
// hash password for validation
$password = sha1($password);
$this->log("Attempting to login with $username / $password: (".__FUNCTION__.":".__LINE__.")", NULL);
$user = NULL;
// find the user that has the right username/password
foreach($this->data['users'] AS $k => $v)
{
if($v['email'] == $username AND $v['password'] == $password)
{
$user = $v;
break;
}
}
$this->log("Exiting login: (".__FUNCTION__.":".__LINE__.")", $user);
return $user;
}
public function savePost($post_info)
{
$this->log("Entering savePost: (".__FUNCTION__.":".__LINE__.")", $post_info);
$mydata = array();
// check for existing data
if(isset($post_info['id']) AND $this->data['posts'][$post_info['id']])
{
$mydata = $this->data['posts'][$post_info['id']];
$this->log("Loaded prior posts: ".print_r($mydata, TRUE)." (".__FUNCTION__.":".__LINE__.")");
}
$this->log("Before copying over existing values: (".__FUNCTION__.":".__LINE__.")", $mydata);
foreach($post_info AS $k => $v)
{
$mydata[$k] = $post_info[$k];
}
$this->log("After copying over existing values: (".__FUNCTION__.":".__LINE__.")", $mydata);
// check required fields
if($this->validatePost($mydata))
{
// if no id, add the next available one
if(!isset($mydata['id']) OR (int)$mydata['id'] < 1)
{
$this->log("No id set: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")");
if(count($this->data['posts']) == 0)
{
$mydata['id'] = 1;
$this->log("Setting id to 1: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")");
}
else
{
$mydata['id'] = max(array_keys($this->data['posts']))+1;
$this->log("Found max id and added 1 [".$mydata['id']."]: ".DataRepository::DATAFILE." (".__FUNCTION__.":".__LINE__.")");
}
}
// set created date if null
if(!isset($mydata['created_at']))
{
$mydata['created_at'] = date ("Y-m-d H:i:s", time());
}
// update modified time
$mydata['modified_at'] = date ("Y-m-d H:i:s", time());
// copy into data and save
$this->data['posts'][$mydata['id']] = $mydata;
$this->log("Before data save: (".__FUNCTION__.":".__LINE__.")", $this->data);
$this->writeTheData();
}
return TRUE;
}
public function getAllPosts()
{
return $this->loadPostsUsers($this->data['posts']);
}
public function loadPostsUsers($posts)
{
foreach($posts AS $id => $post)
{
$posts[$id]['user'] = $this->getUserById($post['user_id']);
}
return $posts;
}
public function dump($line_number, $temp = 'NO')
{
// if(DataRepository::$debug)
{
if($temp == 'NO')
{
$temp = $this->data;
}
echo "<pre>Dumping from line: $line_number\n";
echo json_encode($temp, JSON_PRETTY_PRINT);
echo "</pre>";
}
}
}
/*
* Change Log
*
* 1.0.0
* - first version
* 1.0.1
* - Added isEmailUnique() function for form validation and precheck on user save
* 1.0.2
* - Fixed getAllPosts() to include the post's user info
* - Added loadPostsUsers() to load one or more posts with their user info
* 1.0.3
* - Added autoload to always add admin Joe.
*/