Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?PHP
- /*
- *
- * Members Registration/Login from AssembledBits
- * 2014-10-08 - 5:55AM
- *
- */
- require_once("class.phpmailer.php");
- require_once("formvalidator.php");
- class Members
- {
- var $admin_email;
- var $sitename;
- var $from_address;
- var $db_username;
- var $db_password;
- var $db_name;
- var $db_table;
- var $db_connection;
- var $rand_key;
- var $error_message;
- /* ==========================================================================
- Initialize database variables
- ========================================================================== */
- function InitDB($host,$username,$password,$database,$table)
- {
- $this->db_host = $host;
- $this->db_username = $username;
- $this->db_password = $password;
- $this->db_name = $database;
- $this->db_table = $table;
- }
- /* ==========================================================================
- Set the admin contact e-mail address
- ========================================================================== */
- function SetAdminEmail($email)
- {
- $this->admin_email = $email;
- }
- /* ==========================================================================
- Set Website Name
- ========================================================================== */
- function SetWebsiteName($sitename)
- {
- $this->sitename = $sitename;
- }
- /* ==========================================================================
- Set Random Key Generation
- ========================================================================== */
- function SetRandomKey($key)
- {
- $this->rand_key = $key;
- }
- /*
- * _______ _______ _______ ______ _______ _______ _______ _______ _______
- * | ___| | | | | |_ _|_ _| | | | __|
- * | ___| | | | ---| | | _| |_| - | |__ |
- * |___| |_______|__|____|______| |___| |_______|_______|__|____|_______|
- *
- */
- /* ==========================================================================
- Register User
- <?php
- if(isset($_POST['submitted']))
- {
- if($members->RegisterUser())
- {
- $members->RedirectToURL("thank-you.html");
- }
- }
- ?>
- <form>
- <input type='hidden' name='submitted' id='submitted' value='1'/>
- <input type='text' class='spmhidip' name='<?php echo $members->GetSpamTrapInputName(); ?>' />
- <input type='text' name='user_name' id='user_name' value='<?php echo $members->SafeDisplay('user_name') ?>' maxlength="50" />
- <input type='text' name='user_email' id='user_email' value='<?php echo $members->SafeDisplay('user_email') ?>' maxlength="50" />
- <input type='password' name='user_password' id='password' maxlength="50" />
- </form>
- ========================================================================== */
- function RegisterUser()
- {
- if(!isset($_POST['submitted']))
- {
- return false;
- }
- $formvars = array();
- if(!$this->ValidateRegistrationSubmission())
- {
- return false;
- }
- $this->CollectRegistrationSubmission($formvars);
- if(!$this->SaveToDatabase($formvars))
- {
- return false;
- }
- if(!$this->SendUserConfirmationEmail($formvars))
- {
- return false;
- }
- $this->SendAdminIntimationEmail($formvars);
- return true;
- }
- /* ==========================================================================
- Confirm User
- <label for='code'>Confirmation Code:*
- <input type='text' name='code' id='code' maxlength="50" />
- </label>
- <?php
- if(isset($_GET['code']))
- {
- if($members->ConfirmUser())
- {
- $members->RedirectToURL("thank-you-regd.html");
- }
- }
- ?>
- ========================================================================== */
- function ConfirmUser()
- {
- if(empty($_GET['code'])||strlen($_GET['code'])<=10)
- {
- $this->HandleError("Please provide the confirm code");
- return false;
- }
- $user_rec = array();
- if(!$this->UpdateDBRecForConfirmation($user_rec))
- {
- return false;
- }
- $this->SendUserWelcomeEmail($user_rec);
- $this->SendAdminIntimationOnRegComplete($user_rec);
- return true;
- }
- /* ==========================================================================
- Login
- <input type='hidden' name='submitted' id='submitted' value='1'/>
- <?php
- if(isset($_POST['submitted']))
- {
- if($members->Login())
- {
- $members->RedirectToURL("login-home.php");
- }
- }
- ?>
- ========================================================================== */
- function Login()
- {
- if(empty($_POST['user_email']))
- {
- $this->HandleError("Email is empty!");
- return false;
- }
- if(empty($_POST['user_password']))
- {
- $this->HandleError("Password is empty!");
- return false;
- }
- $email = trim($_POST['user_email']);
- $password = trim($_POST['user_password']);
- if(!isset($_SESSION)){ session_start(); }
- if(!$this->CheckLoginInDB($email,$password))
- {
- return false;
- }
- $_SESSION[$this->GetLoginSessionVar()] = $email;
- return true;
- }
- /* ==========================================================================
- Check Login
- !! Put at the top of any access controlled document
- <?PHP
- require_once("membersite_config.php");
- if(!$members->CheckLogin())
- {
- $members->RedirectToURL("login.php");
- exit;
- }
- ?>
- ========================================================================== */
- function CheckLogin()
- {
- if(!isset($_SESSION)){ session_start(); }
- $sessionvar = $this->GetLoginSessionVar();
- if(empty($_SESSION[$sessionvar]))
- {
- return false;
- }
- return true;
- }
- /* ==========================================================================
- Log Out
- <?php
- $members->LogOut();
- ?>
- ========================================================================== */
- function LogOut()
- {
- session_start();
- $sessionvar = $this->GetLoginSessionVar();
- $_SESSION[$sessionvar]=NULL;
- unset($_SESSION[$sessionvar]);
- }
- /* ==========================================================================
- User Fullname (SESSION)
- Logged in as: <?= $members->UserFullName() ?>
- ========================================================================== */
- function UserFullName()
- {
- return isset($_SESSION['user_name'])?$_SESSION['user_name']:'';
- }
- /* ==========================================================================
- User Email (SESSION)
- <input type="text" id="user_email" name="user_email" value="<?= $members->UserEmail() ?>" />
- ========================================================================== */
- function UserEmail()
- {
- return isset($_SESSION['user_email'])?$_SESSION['user_email']:'';
- }
- /* ==========================================================================
- Checks the database for the submitted email and if matches, will send an
- email for the password reset url
- <?php
- $emailsent = false;
- if(isset($_POST['submitted']))
- {
- if($members->EmailResetPasswordLink())
- {
- $members->RedirectToURL("reset-pwd-link-sent.html");
- exit;
- }
- }
- ?>
- */
- function EmailResetPasswordLink()
- {
- if(empty($_POST['user_email']))
- {
- $this->HandleError("Email is empty!");
- return false;
- }
- $user_rec = array();
- if(false === $this->GetUserFromEmail($_POST['user_email'], $user_rec))
- {
- return false;
- }
- if(false === $this->SendResetPasswordLink($user_rec))
- {
- return false;
- }
- return true;
- }
- /* ==========================================================================
- Reset Password
- <?php
- $success = false;
- if($members->ResetPassword())
- {
- $success=true;
- }
- ?>
- <?php
- if($success){
- ?>
- <h2>Password is Reset Successfully</h2>
- <p>Your new password is sent to your email address.</p>
- <?php
- }else{
- ?>
- <h2>Error</h2>
- <span class='error'><?php echo $members->GetErrorMessage(); ?></span>
- <?php
- }
- ?>
- ========================================================================== */
- function ResetPassword()
- {
- if(empty($_GET['user_email']))
- {
- $this->HandleError("Email is empty!");
- return false;
- }
- if(empty($_GET['code']))
- {
- $this->HandleError("reset code is empty!");
- return false;
- }
- $email = trim($_GET['user_email']);
- $code = trim($_GET['code']);
- if($this->GetResetPasswordCode($email) != $code)
- {
- $this->HandleError("Bad reset code!");
- return false;
- }
- $user_rec = array();
- if(!$this->GetUserFromEmail($email,$user_rec))
- {
- return false;
- }
- $new_password = $this->ResetUserPasswordInDB($user_rec);
- if(false === $new_password || empty($new_password))
- {
- $this->HandleError("Error updating new password");
- return false;
- }
- if(false == $this->SendNewPassword($user_rec,$new_password))
- {
- $this->HandleError("Error sending new password");
- return false;
- }
- return true;
- }
- /* ==========================================================================
- Change Password
- checks if form was submitted, if successful, will redirect
- <input type='hidden' name='submitted' id='submitted' value='1'/>
- <?php
- if(isset($_POST['submitted']))
- {
- if($members->ChangePassword())
- {
- $members->RedirectToURL("changed-pwd.html");
- }
- }
- ?>
- ========================================================================== */
- function ChangePassword()
- {
- if(!$this->CheckLogin())
- {
- $this->HandleError("Not logged in!");
- return false;
- }
- if(empty($_POST['oldpwd']))
- {
- $this->HandleError("Old password is empty!");
- return false;
- }
- if(empty($_POST['newpwd']))
- {
- $this->HandleError("New password is empty!");
- return false;
- }
- $user_rec = array();
- if(!$this->GetUserFromEmail($this->UserEmail(),$user_rec))
- {
- return false;
- }
- $pwd = trim($_POST['oldpwd']);
- $salt = $user_rec['user_salt'];
- $hash = $this->checkhashSSHA($salt, $pwd);
- if($user_rec['user_password'] != $hash)
- {
- $this->HandleError("The old password does not match!");
- return false;
- }
- $newpwd = trim($_POST['newpwd']);
- if(!$this->ChangePasswordInDB($user_rec, $newpwd))
- {
- return false;
- }
- return true;
- }
- /*
- * ______ _______ ______ _____ _______ ______ _______ _______ _____ ______ _______ ______ _______
- * | __ \ | | __ \ |_|_ _| | | | | ___| |_| __ \ ___| __ \ __|
- * | __/ | | __ < |_| |_| ---| | | ___| | __/ ___| <__ |
- * |___| |_______|______/_______|_______|______| |___|___|_______|_______|___| |_______|___|__|_______|
- *
- */
- /* ==========================================================================
- Get Self
- ========================================================================== */
- function GetSelfScript()
- {
- return htmlentities($_SERVER['PHP_SELF']);
- }
- /* ==========================================================================
- Safe Display
- ========================================================================== */
- function SafeDisplay($value_name)
- {
- if(empty($_POST[$value_name]))
- {
- return'';
- }
- return htmlentities($_POST[$value_name]);
- }
- /* ==========================================================================
- Redirect To URL
- ========================================================================== */
- function RedirectToURL($url)
- {
- header("Location: $url");
- exit;
- }
- /* ==========================================================================
- Spam Trap
- <input type='text' class='spmhidip' name='<?php echo $members->GetSpamTrapInputName(); ?>' />
- ========================================================================== */
- function GetSpamTrapInputName()
- {
- return 'sp'.md5('KHGdnbvsgst'.$this->rand_key);
- }
- /* ==========================================================================
- Error Message
- Displays error on script page
- <div>
- <span class='error'>
- <?php echo $members->GetErrorMessage(); ?>
- </span>
- </div>
- ========================================================================== */
- function GetErrorMessage()
- {
- if(empty($this->error_message))
- {
- return '';
- }
- $errormsg = nl2br(htmlentities($this->error_message));
- return $errormsg;
- }
- /*
- * ______ ______ _______ ___ ___ _______ _______ _______ _______ _______ _____ ______ _______ ______ _______
- * | __ \ __ \_ _| | | _ |_ _| ___| | | | ___| |_| __ \ ___| __ \ __|
- * | __/ <_| |_| | | | | | | ___| | | ___| | __/ ___| <__ |
- * |___| |___|__|_______|\_____/|___|___| |___| |_______| |___|___|_______|_______|___| |_______|___|__|_______|
- *
- */
- /* ==========================================================================
- Error Handler
- ========================================================================== */
- function HandleError($err, $sqlerr = null)
- {
- $this->error_message .= $err."\r\n";
- if($sqlerr) {
- $this->error_message .= $sqlerr."\r\n";
- }
- }
- /* ==========================================================================
- Handle DB Errors
- ========================================================================== */
- function HandleDBError($err, $sqlerr = null)
- {
- $this->HandleError($err, $sqlerr);
- }
- /* ==========================================================================
- Get 'From' Address
- ========================================================================== */
- function GetFromAddress()
- {
- if(!empty($this->from_address))
- {
- return $this->from_address;
- }
- $host = $_SERVER['SERVER_NAME'];
- $from ="info@$host";
- return $from;
- }
- /* ==========================================================================
- Get Login Session
- ========================================================================== */
- function GetLoginSessionVar()
- {
- $retvar = md5($this->rand_key);
- $retvar = 'usr_'.substr($retvar,0,10);
- return $retvar;
- }
- /* ==========================================================================
- Check User Login in DB
- ========================================================================== */
- function CheckLoginInDB($email,$password)
- {
- if(!$this->DBLogin())
- {
- $this->HandleError("Database login failed!");
- return false;
- }
- $check_db_for_email_stmt = $this->db->prepare("SELECT * FROM $this->db_table WHERE user_email = :user_email");
- $check_db_for_email_stmt->execute(array('user_email' => $email));
- $result = $check_db_for_email_stmt->fetchAll();
- if($result) {
- $salt = $result[0]['salt'];
- $encrypted_password = $result[0]['password'];
- $hash = $this->checkhashSSHA($salt, $password);
- }
- $user_login_stmt = $this->db->prepare("Select user_name, user_email from $this->db_table where user_email = :user_email and user_password = :hash and user_confirmcode='y'");
- $user_login_stmt->execute(array('user_email' => $email, 'user_password' => $hash));
- $result = $user_login_stmt->fetchAll();
- if(!$result)
- {
- $this->HandleError("Error logging in. The username or password does not match");
- return false;
- }
- $_SESSION['user_name'] = $result[0]['user_name'];
- $_SESSION['user_email'] = $result[0]['user_email'];
- return true;
- }
- /* ==========================================================================
- Check Hash
- ========================================================================== */
- public function checkhashSSHA($salt, $password)
- {
- $hash = base64_encode(sha1($password . $salt, true) . $salt);
- return $hash;
- }
- /* ==========================================================================
- Update DB on Registration confirmation
- ========================================================================== */
- function UpdateDBRecForConfirmation(&$user_rec)
- {
- if(!$this->DBLogin())
- {
- $this->HandleError("Database login failed!");
- return false;
- }
- $confirmcode = $_GET['code'];
- $check_confirmation_code_stmt = $this->db->prepare("Select user_name, user_email from $this->db_table where user_confirmcode = :user_confirmcode");
- $check_confirmation_code_stmt->execute(array('user_confirmcode' => $confirmcode));
- $result = $check_confirmation_code_stmt->fetchAll();
- if(!$result) {
- $this->HandleError("Wrong confirm code");
- return false;
- }
- $row = $result[0];
- $user_rec['user_name'] = $row['user_name'];
- $user_rec['user_email'] = $row['user_email'];
- try {
- $update_confirmation_code_stmt = $this->db->prepare("Update $this->db_table Set user_confirmcode = 'y' Where user_confirmcode = :user_confirmcode");
- $update_confirmation_code_stmt->execute(array('user_confirmcode' => $confirmcode));
- } catch(PDOException $e) {
- $this->HandleDBError("Error inserting data to the table", $e->getMessage());
- return false;
- }
- return true;
- }
- /* ==========================================================================
- Reset user password in DB
- ========================================================================== */
- function ResetUserPasswordInDB($user_rec)
- {
- $new_password = substr(md5(uniqid()),0,10);
- if(false == $this->ChangePasswordInDB($user_rec,$new_password))
- {
- return false;
- }
- return $new_password;
- }
- /* ==========================================================================
- Change password in DB
- ========================================================================== */
- function ChangePasswordInDB($user_rec, $newpwd)
- {
- $hash = $this->hashSSHA($newpwd);
- $new_password = $hash["encrypted"];
- $salt = $hash["salt"];
- try {
- $change_password_in_db = $this->db->prepare("Update $this->db_table Set user_password = :user_password, user_salt = :user_salt Where user_id = :user_id");
- $change_password_in_db->execute(array('user_password' => $new_password, 'user_salt' => $salt, 'user_id' => $user_rec['user_id']));
- } catch(PDOException $e) {
- $this->HandleDBError("Error updating the password", $e->getMessage());
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function GetUserFromEmail($email,&$user_rec)
- {
- if(!$this->DBLogin())
- {
- $this->HandleError("Database login failed!");
- return false;
- }
- $get_user_from_email_stmt = $this->db->prepare("Select * from $this->db_table where user_email = :user_email");
- $get_user_from_email_stmt->execute(array(':user_email' => $email));
- $result = $get_user_from_email_stmt->fetchAll();
- if(!$result)
- {
- $this->HandleError("There is no user with email: $email");
- return false;
- }
- $user_rec = $result[0];
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function SendUserWelcomeEmail(&$user_rec)
- {
- $mailer = new PHPMailer();
- $mailer->CharSet = 'utf-8';
- $mailer->AddAddress($user_rec['user_email'],$user_rec['user_name']);
- $mailer->Subject = "Welcome to ".$this->sitename;
- $mailer->From = $this->GetFromAddress();
- $mailer->Body ="Hello ".$user_rec['user_name']."\r\n\r\n".
- "Welcome! Your registration with ".$this->sitename." is completed.\r\n".
- "\r\n".
- "Regards,\r\n".
- "Webmaster\r\n".
- $this->sitename;
- if(!$mailer->Send())
- {
- $this->HandleError("Failed sending user welcome email.");
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function SendAdminIntimationOnRegComplete(&$user_rec)
- {
- if(empty($this->admin_email))
- {
- return false;
- }
- $mailer = new PHPMailer();
- $mailer->CharSet = 'utf-8';
- $mailer->AddAddress($this->admin_email);
- $mailer->Subject = "Registration Completed: ".$user_rec['user_name'];
- $mailer->From = $this->GetFromAddress();
- $mailer->Body ="A new user registered at ".$this->sitename."\r\n".
- "Name: ".$user_rec['user_name']."\r\n".
- "Email address: ".$user_rec['user_email']."\r\n";
- if(!$mailer->Send())
- {
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function GetResetPasswordCode($email)
- {
- return substr(md5($email.$this->sitename.$this->rand_key),0,10);
- }
- /* ==========================================================================
- ========================================================================== */
- function SendResetPasswordLink($user_rec)
- {
- $email = $user_rec['user_email'];
- $mailer = new PHPMailer();
- $mailer->CharSet = 'utf-8';
- $mailer->AddAddress($email,$user_rec['user_name']);
- $mailer->Subject = "Your reset password request at ".$this->sitename;
- $mailer->From = $this->GetFromAddress();
- $link = $this->GetAbsoluteURLFolder().
- '/resetpwd.php?email='.
- urlencode($email).'&code='.
- urlencode($this->GetResetPasswordCode($email));
- $mailer->Body ="Hello ".$user_rec['user_name']."\r\n\r\n".
- "There was a request to reset your password at ".$this->sitename."\r\n".
- "Please click the link below to complete the request: \r\n".$link."\r\n".
- "Regards,\r\n".
- "Webmaster\r\n".
- $this->sitename;
- if(!$mailer->Send())
- {
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function SendNewPassword($user_rec, $new_password)
- {
- $email = $user_rec['user_email'];
- $mailer = new PHPMailer();
- $mailer->CharSet = 'utf-8';
- $mailer->AddAddress($email,$user_rec['user_name']);
- $mailer->Subject = "Your new password for ".$this->sitename;
- $mailer->From = $this->GetFromAddress();
- $mailer->Body ="Hello ".$user_rec['user_name']."\r\n\r\n".
- "Your password is reset successfully. ".
- "Here is your updated login:\r\n".
- "username:".$user_rec['user_name']."\r\n".
- "password:$new_password\r\n".
- "\r\n".
- "Login here: ".$this->GetAbsoluteURLFolder()."/login.php\r\n".
- "\r\n".
- "Regards,\r\n".
- "Webmaster\r\n".
- $this->sitename;
- if(!$mailer->Send())
- {
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function ValidateRegistrationSubmission()
- {
- //This is a hidden input field. Humans won't fill this field.
- if(!empty($_POST[$this->GetSpamTrapInputName()]) )
- {
- //The proper error is not given intentionally
- $this->HandleError("Automated submission prevention: case 2 failed");
- return false;
- }
- $validator = new FormValidator();
- $validator->addValidation("user_name","req","Please fill in Name");
- $validator->addValidation("user_email","email","The input for Email should be a valid email value");
- $validator->addValidation("user_email","req","Please fill in Email");
- $validator->addValidation("user_password","req","Please fill in Password");
- if(!$validator->ValidateForm())
- {
- $error='';
- $error_hash = $validator->GetErrors();
- foreach($error_hash as $inpname => $inp_err)
- {
- $error .= $inpname.':'.$inp_err."\n";
- }
- $this->HandleError($error);
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function CollectRegistrationSubmission(&$formvars)
- {
- $formvars['user_name'] = $this->Sanitize($_POST['user_name']);
- $formvars['user_email'] = $this->Sanitize($_POST['user_email']);
- $formvars['user_phone'] = $this->Sanitize($_POST['user_phone']);
- $formvars['user_password'] = $this->Sanitize($_POST['user_password']);
- $confirmcode = $this->MakeConfirmationMd5($formvars['user_email']);
- $formvars['user_confirmcode'] = $confirmcode;
- }
- /* ==========================================================================
- ========================================================================== */
- function SendUserConfirmationEmail(&$formvars)
- {
- $mailer = new PHPMailer();
- $mailer->CharSet = 'utf-8';
- $mailer->AddAddress($formvars['user_email'],$formvars['user_name']);
- $mailer->Subject = "Your registration with ".$this->sitename;
- $mailer->From = $this->GetFromAddress();
- $confirmcode = $formvars['user_confirmcode'];
- $confirm_url = $this->GetAbsoluteURLFolder().'/confirmreg.php?code='.$confirmcode;
- $mailer->Body ="Hello ".$formvars['user_name']."\r\n\r\n".
- "Thanks for your registration with ".$this->sitename."\r\n".
- "Please click the link below to confirm your registration.\r\n".
- "$confirm_url\r\n".
- "\r\n".
- "Regards,\r\n".
- "Webmaster\r\n".
- $this->sitename;
- if(!$mailer->Send())
- {
- $this->HandleError("Failed sending registration confirmation email.");
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function GetAbsoluteURLFolder()
- {
- $scriptFolder = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';
- $urldir ='';
- $pos = strrpos($_SERVER['REQUEST_URI'],'/');
- if(false !==$pos)
- {
- $urldir = substr($_SERVER['REQUEST_URI'],0,$pos);
- }
- $scriptFolder .= $_SERVER['HTTP_HOST'].$urldir;
- return $scriptFolder;
- }
- /* ==========================================================================
- ========================================================================== */
- function SendAdminIntimationEmail(&$formvars)
- {
- if(empty($this->admin_email))
- {
- return false;
- }
- $mailer = new PHPMailer();
- $mailer->CharSet = 'utf-8';
- $mailer->AddAddress($this->admin_email);
- $mailer->Subject = "New registration: ".$formvars['user_name'];
- $mailer->From = $this->GetFromAddress();
- $mailer->Body ="A new user registered at ".$this->sitename."\r\n".
- "Name: ".$formvars['user_name']."\r\n".
- "Email address: ".$formvars['user_email']."\r\n".
- "Phone number: ".$formvars['user_phone'];
- if(!$mailer->Send())
- {
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function SaveToDatabase(&$formvars)
- {
- if(!$this->DBLogin())
- {
- $this->HandleError("Database login failed!");
- return false;
- }
- if(!$this->Ensuretable())
- {
- return false;
- }
- if(!$this->IsFieldUnique($formvars,'user_email'))
- {
- $this->HandleError("This email is already registered");
- return false;
- }
- if(!$this->InsertIntoDB($formvars))
- {
- $this->HandleError("Inserting to Database failed!");
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function IsFieldUnique($formvars,$fieldname)
- {
- $fieldname = $this->db->quote($fieldname);
- $is_field_unique_stmt = $this->db->prepare("select user_email from $this->db_table where $fieldname = :fieldname");
- $is_field_unique_stmt->execute(array('fieldname' => $formvars[$fieldname]));
- $result = $is_field_unique_stmt->fetchAll();
- // if there is a result (field is not unique), return false
- if($result)
- {
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function DBLogin()
- {
- try {
- $this->db = new PDO("mysql:dbname={$this->db_name};host={$this->db_host};charset=utf8", $this->db_username, $this->db_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
- } catch(PDOException $e) {
- $this->HandleDBError("Database Login failed! Please make sure that the DB login credentials provided are correct", $e->getMessage());
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function Ensuretable()
- {
- try {
- $ensure_table_stmt = $this->db->query("select 1 from $this->db_table");
- $result = $ensure_table_stmt->fetchAll();
- } catch (PDOException $e) {
- // We got an exception == table not found
- $result = false;
- }
- // if result is false user table is created
- if(!$result) {
- return $this->CreateTable();
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function CreateTable()
- {
- $create_table_stmt = "Create Table $this->db_table (".
- "user_id INT NOT NULL AUTO_INCREMENT ,".
- "user_name VARCHAR( 128 ) NOT NULL ,".
- "user_email VARCHAR( 64 ) NOT NULL ,".
- "user_phone VARCHAR( 16 ) ,".
- "user_salt VARCHAR( 50 ) NOT NULL ,".
- "user_stripe_id VARCHAR( 64 ) ,".
- "user_password VARCHAR( 80 ) NOT NULL ,".
- "user_confirmcode VARCHAR(32) ,".
- "PRIMARY KEY ( user_id )".
- ")";
- try {
- $this->db->query($create_table_stmt);
- } catch(PDOException $e) {
- $this->HandleDBError("Error creating the table", $e->getMessage());
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function InsertIntoDB(&$formvars)
- {
- $hash = $this->hashSSHA($formvars['user_password']);
- $encrypted_password = $hash["encrypted"];
- $salt = $hash["salt"];
- try {
- $insert_user_stmt = $this->db->prepare("INSERT INTO $this->db_table
- (user_name, user_email, user_phone, user_password, user_salt, user_stripe_id, user_confirmcode)
- VALUES
- (:user_name,:user_email,:user_phone,:user_password,:user_salt,:user_stripe_id,:user_confirmcode)");
- $insert_user_stmt->execute( array( 'user_name' => $formvars['user_name'],
- 'user_email' => $formvars['user_email'],
- 'user_phone' => $formvars['user_phone'],
- 'user_password' => $encrypted_password,
- 'user_salt' => $salt,
- 'user_stripe_id' => $formvars['user_stripe_id'],
- 'user_confirmcode' => $formvars['user_confirmcode']));
- } catch(PDOException $e) {
- $this->HandleDBError("Error inserting data to the table", $e->getMessage());
- return false;
- }
- return true;
- }
- /* ==========================================================================
- ========================================================================== */
- function hashSSHA($password)
- {
- $salt = sha1(rand());
- $salt = substr($salt, 0, 10);
- $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
- $hash = array("salt" => $salt, "encrypted" => $encrypted);
- return $hash;
- }
- /* ==========================================================================
- ========================================================================== */
- function MakeConfirmationMd5($email)
- {
- $randno1 = rand();
- $randno2 = rand();
- return md5($email.$this->rand_key.$randno1.''.$randno2);
- }
- /* ==========================================================================
- Sanitize() function removes any potential threat from the
- data submitted. Prevents email injections or any other hacker attempts.
- if $remove_nl is true, newline chracters are removed from the input.
- ========================================================================== */
- function Sanitize($str,$remove_nl=true)
- {
- if($remove_nl)
- {
- $injections = array('/(\n+)/i',
- '/(\r+)/i',
- '/(\t+)/i',
- '/(%0A+)/i',
- '/(%0D+)/i',
- '/(%08+)/i',
- '/(%09+)/i'
- );
- $str = preg_replace($injections,'',$str);
- }
- return $str;
- }
- } // end of Members() class
Add Comment
Please, Sign In to add comment