Hello All,
My first post here, hope I don;t scare everyone. I’m Alan form Vancouver Canada, 2 months into php and still a newbie. Please excuse my grammar, English is not my native tongue.
my question:
I am working on developing a profile page for users of my site. one area of the site is to register an application to rent a unit in my building. part of the process of the application requires a user to write their social insurance number. I have picked up a neat little javascript utility that validate Canadian SIN with 3 input fields on a form. once the SN has been validated I then concatenate the 3 fields into one to make a complete SIN number xxx-xxx-xxx and save it into my database. all that works really well. Teh problem that I have is to explode this concatenated SIN number that was saved into my database back into the 3 input fields on the form if a user need to update their profile. I have been working at this for 3 days and have had that question floating in two other forum and nobody seems to know how I can do that. Are there any super Nija php coders in here that can help me?
here is what I have so far: NOTE: I included the whole thing in the event you are curious about different aspect of my script. Thanks a bunch for looking this over for me. I would truly appreciate feedback
page and form:
<?php
include_once 'core/init.php';
$general->logged_out_protect();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css" >
<title>Settings</title>
<script>
function disableEnterKey(e){
var key;
if (window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if (key == 13)
return false;
else
return true;
}
</script>
<script type="text/javascript">
// this is a javascript sin number checker from http://www.codingforums.com/showthread.php?t=279032
// valid number examples 046-454-286 193-456-787 127-248-623
var sin = 0;
function validate(which,next) {
var val = which.value;
val = val.replace(/[^0-9]/g,"")
which.value = val;
next = "S" + next;
if (val.length == 3) {
document.getElementById(next).focus();
}
sin = document.getElementById("S1").value + document.getElementById("S2").value + document.getElementById("S3").value;
}
function CheckNumber(sin) { // sin is a string value
var c = 0;
if (sin.substring(0,3) == "000") {
alert("Invalid SIN: SIN's can't start with 000.");
document.getElementById("S1").value = ""; // clear the fields
document.getElementById("S2").value = "";
document.getElementById("S3").value = "";
//document.getElementById("S1").focus(); // if required
return false;
}
if (sin.length !=9) {
alert ("You must complete all three fields!");
return false;
}
// odd digits
for (var i = 1; i<=9; i+=2) {
c += Number(sin.charAt(i-1));
}
// even digits
for (var i = 2; i <=8; i+=2) {
var digit = Number(sin.charAt(i-1)) *2;
if (digit >9) {digit = digit -9}
c += digit;
}
sin = document.getElementById("S1").value + "-" + document.getElementById("S2").value + "-" +document.getElementById("S3").value;
if ((c%10) == 0) {
alert ("The Social Insurance Number " + sin + " is valid");
}
else {
alert ("The Social Insurance Number " + sin + " is NOT valid");
return false;
}
}
</script>
</head>
<body>
<div id="container">
<?php include 'includes/menu.php'; ?>
<?php
if (isset($_GET['success']) && empty($_GET['success'])) {
echo '<h3>Your details have been updated!</h3>';
} else{
if(empty($_POST) === false) {
if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
if (ctype_alpha($_POST['first_name']) === false) {
$errors[] = 'Please enter your First Name with only letters!';
}
}
if (isset($_POST['middle_name']) && !empty ($_POST['middle_name'])){
if (ctype_alpha($_POST['middle_name']) === false) {
$errors[] = 'Please enter your Middle Name with only letters!';
}
}
if (isset($_POST['last_name']) && !empty ($_POST['last_name'])){
if (ctype_alpha($_POST['last_name']) === false) {
$errors[] = 'Please enter your Last Name with only letters!';
}
}
$date = $users->parseDate($_POST['dob']);
if ($date) {
$dob = $date->format('Y-m-d');
}
if (isset($_POST['gender']) && !empty($_POST['gender'])) {
$allowed_gender = array('undisclosed', 'Male', 'Female');
if (in_array($_POST['gender'], $allowed_gender) === false) {
$errors[] = 'Please choose a Gender from the list';
}
}
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name'])) {
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif' );
$a = explode('.', $name);
$file_ext = strtolower(end($a)); unset($a);
$file_size = $_FILES['myfile']['size'];
$path = "avatars";
if (in_array($file_ext, $allowed_ext) === false) {
$errors[] = 'Image file type not allowed';
}
if ($file_size > 2097152) {
$errors[] = 'File size must be under 2mb';
}
} else {
$newpath = $user['image_location'];
}
if(empty($errors) === true) {
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name']) && $_POST['use_default'] != 'on') {
$newpath = $general->file_newpath($path, $name);
move_uploaded_file($tmp_name, $newpath);
}else if(isset($_POST['use_default']) && $_POST['use_default'] === 'on'){
$newpath = 'avatars/default_avatar.png';
}
$first_name = htmlentities(trim($_POST['first_name']));
$last_name = htmlentities(trim($_POST['last_name']));
$middle_name = htmlentities(trim($_POST['middle_name']));
$gender = htmlentities(trim($_POST['gender']));
//$dob = htmlentities(trim($_POST['dob']));
$sin = htmlentities(trim($_POST['sin']));
$bio = htmlentities(trim($_POST['bio']));
$image_location = htmlentities(trim($newpath));
//list($s1, $s2, $s3) = explode('-', $sin); this is not working-------------------------------------------------------------------
//this is where I try to explode the value
$sin = $sin1 ."-". $sin2 ."-". $sin3;
$s = explode("-", $sin);
$s[0] = $_POST['S1'];
$s[1] = $_POST['S2'];
$s[2] = $_POST['S3'];
echo $sin1;
//--------------------------------------------------------------------this is my calling function-----------------------------------------------------------
$users->update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $bio, $image_location, $user_id);
header('Location: settings.php?success');
exit();
} else if (empty($errors) === false) {
echo '<p>' . implode('</p><p>', $errors) . '</p>';
}
}
?>
<h2>Settings.</h2> <p><b>Note: Information you post here is made viewable to others.</b></p>
<hr />
<form action="" method="post" enctype="multipart/form-data">
<div id="profile_picture">
<h3>Change Profile Picture</h3>
<ul>
<?php
if(!empty ($user['image_location'])) {
$image = $user['image_location'];
echo "<img src='$image'>";
}
?>
<li>
<input type="file" name="myfile" />
</li>
<?php if($image != 'avatars/default_avatar.png'){ ?>
<li>
<input type="checkbox" name="use_default" id="use_default" /> <label for="use_default">Use default picture</label>
</li>
<?php
}
?>
</ul>
</div>
<div id="personal_info">
<h3 >Change Profile Information </h3>
<ul>
<li>
<h4>First name:</h4>
<input type="text" name="first_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['first_name']) ){echo htmlentities(strip_tags($_POST['first_name']));} else { echo $user['first_name']; }?>">
</li>
<li>
<h4>Middle name:</h4>
<input type="text" name="middle_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['middle_name']) ){echo htmlentities(strip_tags($_POST['middle_name']));} else { echo $user['middle_name']; }?>">
</li>
<li>
<h4>Last name: </h4>
<input type="text" name="last_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['last_name']) ){echo htmlentities(strip_tags($_POST['last_name']));} else { echo $user['last_name']; }?>">
</li>
<li>
<h4>Gender:</h4>
<?php
$gender = $user['gender'];
$options = array("undisclosed", "Male", "Female");
echo '<select name="gender">';
foreach($options as $option){
if($gender == $option){
$sel = 'selected="selected"';
}else{
$sel='';
}
echo '<option '. $sel .'>' . $option . '</option>';
}
?>
</select>
</li>
<li>
<h4>D.O.B (YYYY-MM-DD #:</h4>
<input type="date ('yyyy-mm-dd')" name="dob" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['dob']) ){echo htmlentities(strip_tags($_POST['dob']));} else { echo $user['dob']; }?>">
</li>
<li>
<br><br>
THIS IS THE FORM BELOW_______________________________________________________________________________________
Social Insurance Number <input type = "text" id = "S1" name="S1" size =" 3" maxlength = "3" onkeyup = "validate(this,2)" value="<?php if (isset($s[0]) ){echo htmlentities(strip_tags($s[0]));} else { echo $user['S1']; }?>>
<input type = "text" id = "S2" name="S2" size =" 3" maxlength = "3" onkeyup = "validate(this,3)" value="<?php echo $s2;?>">
<input type = "text" id = "S3" name="S3" size =" 3" maxlength = "3" onkeyup = "validate(this,3)"value="<?php echo $s3;?>">
<br/><br/>
<input type="button" value="Validate Number" onclick="CheckNumber(sin)"/>
</li>
<?php /* <h4>Social Insurance #:</h4>
<input type="text" name="sin" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['sin']) ){echo htmlentities(strip_tags($_POST['sin']));} else { echo $user['sin']; }?>">
</li> */?>
<li>
<h4>Bio:</h4>
<textarea name="bio"><?php if (isset($_POST['bio']) ){echo htmlentities(strip_tags($_POST['bio']));} else { echo $user['bio']; }?></textarea>
</li>
</ul>
</div>
<div class="clear"></div>
<hr />
<span>Update Changes:</span>
<input type="submit" value="Update">
</form>
</div>
</body>
</html>
<?php
}
This is my user Class and User_update function---------------
<?php
class Users{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $bio, $image_location, $id){
$query = $this->db->prepare("UPDATE `users` SET
`first_name` = ?,
`middle_name` = ?,
`last_name` = ?,
`gender` = ?,
`dob` = ?,
`sin` = ?,
`bio` = ?,
`image_location`= ?
WHERE `id` = ?
");
$query->bindValue(1, $first_name);
$query->bindValue(2, $middle_name);
$query->bindValue(3, $last_name);
$query->bindValue(4, $gender);
$query->bindValue(5, $dob);
$query->bindValue(6, $sin);
$query->bindValue(7, $bio);
$query->bindValue(8, $image_location);
$query->bindValue(9, $id);
//$s = explode("-",$sin);
//$sin1=$s[0];
//$sin2=$s[1];
//$sin3=$s[2];
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}
//function created by me to parse date format
public function parseDate($date) {
try {
$dt = new DateTime($date);
return $dt;
} catch (Exception $e) {
try {
$date = str_replace('-', '/', $date);
$dt = new DateTime($date);
return $dt;
} catch (Exception $e) {
return false;
}
}
}
public function change_password($user_id, $password) {
global $bcrypt;
/* Two create a Hash you do */
$password_hash = $bcrypt->genHash($password);
$query = $this->db->prepare("UPDATE `users` SET `password` = ? WHERE `id` = ?");
$query->bindValue(1, $password_hash);
$query->bindValue(2, $user_id);
try{
$query->execute();
return true;
} catch(PDOException $e){
die($e->getMessage());
}
}
public function recover($email, $generated_string) {
if($generated_string == 0){
return false;
}else{
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email` = ? AND `generated_string` = ?");
$query->bindValue(1, $email);
$query->bindValue(2, $generated_string);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
global $bcrypt;
$username = $this->fetch_info('username', 'email', $email); // getting username for the use in the email.
$user_id = $this->fetch_info('id', 'email', $email);// We want to keep things standard and use the user's id for most of the operations. Therefore, we use id instead of email.
$charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$generated_password = substr(str_shuffle($charset),0, 10);
$this->change_password($user_id, $generated_password);
$query = $this->db->prepare("UPDATE `users` SET `generated_string` = 0 WHERE `id` = ?");
$query->bindValue(1, $user_id);
$query->execute();
mail($email, 'Your password', "Hello " . $username . ",\
\
Your your new password is: " . $generated_password . "\
\
Please change your password once you have logged in using this password.\
\
-Example team");
}else{
return false;
}
} catch(PDOException $e){
die($e->getMessage());
}
}
}
public function fetch_info($what, $field, $value){
$allowed = array('id', 'username', 'first_name', 'middle_name','last_name', 'gender', 'dob', 'sin', 'bio', 'email'); // I have only added few, but you can add more. However do not add 'password' eventhough the parameters will only be given by you and not the user, in our system.
if (!in_array($what, $allowed, true) || !in_array($field, $allowed, true)) {
throw new InvalidArgumentException;
}else{
$query = $this->db->prepare("SELECT $what FROM `users` WHERE $field = ?");
$query->bindValue(1, $value);
try{
$query->execute();
} catch(PDOException $e){
die($e->getMessage());
}
return $query->fetchColumn();
}
}
public function confirm_recover($email){
$username = $this->fetch_info('username', 'email', $email);// We want the 'id' WHERE 'email' = user's email ($email)
$unique = uniqid('',true);
$random = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'),0, 10);
$generated_string = $unique . $random; // a random and unique string
$query = $this->db->prepare("UPDATE `users` SET `generated_string` = ? WHERE `email` = ?");
$query->bindValue(1, $generated_string);
$query->bindValue(2, $email);
try{
$query->execute();
mail($email, 'Recover Password', "Hello " . $username. ",\\r\
Please click the link below:\\r\
\\r\
http://www.example.com/recover.php?email=" . $email . "&generated_string=" . $generated_string . "\\r\
\\r\
We will generate a new password for you and send it back to your email.\\r\
\\r\
-- Example team");
} catch(PDOException $e){
die($e->getMessage());
}
}
public function user_exists($username) {
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?");
$query->bindValue(1, $username);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch (PDOException $e){
die($e->getMessage());
}
}
public function email_exists($email) {
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email`= ?");
$query->bindValue(1, $email);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch (PDOException $e){
die($e->getMessage());
}
}
public function register($username, $password, $email){
global $bcrypt; // making the $bcrypt variable global so we can use here
$time = time();
$ip = $_SERVER['REMOTE_ADDR']; // getting the users IP address
$email_code = $email_code = uniqid('code_',true); // Creating a unique string.
$password = $bcrypt->genHash($password);
$query = $this->db->prepare("INSERT INTO `users` (`username`, `password`, `email`, `ip`, `time`, `email_code`) VALUES (?, ?, ?, ?, ?, ?) ");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->bindValue(3, $email);
$query->bindValue(4, $ip);
$query->bindValue(5, $time);
$query->bindValue(6, $email_code);
try{
$query->execute();
mail($email, 'Please activate your account', "Hello " . $username. ",\\r\
Thank you for registering with us. Please visit the link below so we can activate your account:\\r\
\\r\
http://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\\r\
\\r\
-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
public function activate($email, $email_code) {
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email` = ? AND `email_code` = ? AND `confirmed` = ?");
$query->bindValue(1, $email);
$query->bindValue(2, $email_code);
$query->bindValue(3, 0);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
$query_2 = $this->db->prepare("UPDATE `users` SET `confirmed` = ? WHERE `email` = ?");
$query_2->bindValue(1, 1);
$query_2->bindValue(2, $email);
$query_2->execute();
return true;
}else{
return false;
}
} catch(PDOException $e){
die($e->getMessage());
}
}
public function email_confirmed($username) {
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ? AND `confirmed` = ?");
$query->bindValue(1, $username);
$query->bindValue(2, 1);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch(PDOException $e){
die($e->getMessage());
}
}
public function login($username, $password) {
global $bcrypt; // Again make get the bcrypt variable, which is defined in init.php, which is included in login.php where this function is called
$query = $this->db->prepare("SELECT `password`, `id` FROM `users` WHERE `username` = ?");
$query->bindValue(1, $username);
try{
$query->execute();
$data = $query->fetch();
$stored_password = $data['password']; // stored hashed password
$id = $data['id']; // id of the user to be returned if the password is verified, below.
if($bcrypt->verify($password, $stored_password) === true){ // using the verify method to compare the password with the stored hashed password.
return $id; // returning the user's id.
}else{
return false;
}
}catch(PDOException $e){
die($e->getMessage());
}
}
public function userdata($id) {
$query = $this->db->prepare("SELECT * FROM `users` WHERE `id`= ?");
$query->bindValue(1, $id);
try{
$query->execute();
return $query->fetch();
} catch(PDOException $e){
die($e->getMessage());
}
}
public function get_users() {
$query = $this->db->prepare("SELECT * FROM `users` ORDER BY `time` DESC");
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
return $query->fetchAll();
}
}