Guest User

New Paste

a guest
May 28th, 2016
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?PHP
  2. /*
  3.     Registration/Login script from HTML Form Guide
  4.     V1.0
  5.  
  6.     This program is free software published under the
  7.     terms of the GNU Lesser General Public License.
  8.     http://www.gnu.org/copyleft/lesser.html
  9.    
  10.  
  11. This program is distributed in the hope that it will
  12. be useful - WITHOUT ANY WARRANTY; without even the
  13. implied warranty of MERCHANTABILITY or FITNESS FOR A
  14. PARTICULAR PURPOSE.
  15.  
  16. For updates, please visit:
  17. http://www.html-form-guide.com/php-form/php-registration-form.html
  18. http://www.html-form-guide.com/php-form/php-login-form.html
  19.  
  20. */
  21. require_once("class.phpmailer.php");
  22. require_once("formvalidator.php");
  23.  
  24. class FGMembersite
  25. {
  26.     var $admin_email;
  27.     var $from_address;
  28.    
  29.     var $username;
  30.     var $pwd;
  31.     var $database;
  32.     var $tablename;
  33.     var $connection;
  34.     var $rand_key;
  35.    
  36.     var $error_message;
  37.    
  38.     //-----Initialization -------
  39.     function FGMembersite()
  40.     {
  41.         $this->sitename = 'YourWebsiteName.com';
  42.         $this->rand_key = '0iQx5oBk66oVZep';
  43.     }
  44.    
  45.     function InitDB($host,$uname,$pwd,$database,$tablename)
  46.     {
  47.         $this->db_host  = $host;
  48.         $this->username = $uname;
  49.         $this->pwd  = $pwd;
  50.         $this->database  = $database;
  51.         $this->tablename = $tablename;
  52.        
  53.     }
  54.     function SetAdminEmail($email)
  55.     {
  56.         $this->admin_email = $email;
  57.     }
  58.    
  59.     function SetWebsiteName($sitename)
  60.     {
  61.         $this->sitename = $sitename;
  62.     }
  63.    
  64.     function SetRandomKey($key)
  65.     {
  66.         $this->rand_key = $key;
  67.     }
  68.    
  69.     //-------Main Operations ----------------------
  70.     function RegisterUser()
  71.     {
  72.         if(!isset($_POST['submitted']))
  73.         {
  74.            return false;
  75.         }
  76.        
  77.         $formvars = array();
  78.        
  79.         if(!$this->ValidateRegistrationSubmission())
  80.         {
  81.             return false;
  82.         }
  83.        
  84.         $this->CollectRegistrationSubmission($formvars);
  85.        
  86.         if(!$this->SaveToDatabase($formvars))
  87.         {
  88.             return false;
  89.         }
  90.        
  91.         if(!$this->SendUserConfirmationEmail($formvars))
  92.         {
  93.             return false;
  94.         }
  95.  
  96.         $this->SendAdminIntimationEmail($formvars);
  97.        
  98.         return true;
  99.     }
  100.  
  101.     function ConfirmUser()
  102.     {
  103.         if(empty($_GET['code'])||strlen($_GET['code'])<=10)
  104.         {
  105.             $this->HandleError("Please provide the confirm code");
  106.             return false;
  107.         }
  108.         $user_rec = array();
  109.         if(!$this->UpdateDBRecForConfirmation($user_rec))
  110.         {
  111.             return false;
  112.         }
  113.        
  114.         $this->SendUserWelcomeEmail($user_rec);
  115.        
  116.         $this->SendAdminIntimationOnRegComplete($user_rec);
  117.        
  118.         return true;
  119.     }    
  120.    
  121.     function Login()
  122.     {
  123.         if(empty($_POST['username']))
  124.         {
  125.             $this->HandleError("UserName is empty!");
  126.             return false;
  127.         }
  128.        
  129.         if(empty($_POST['password']))
  130.         {
  131.             $this->HandleError("Password is empty!");
  132.             return false;
  133.         }
  134.        
  135.         $username = trim($_POST['username']);
  136.         $password = trim($_POST['password']);
  137.        
  138.         if(!isset($_SESSION)){ session_start(); }
  139.         if(!$this->CheckLoginInDB($username,$password))
  140.         {
  141.             return false;
  142.         }
  143.        
  144.         $_SESSION[$this->GetLoginSessionVar()] = $username;
  145.        
  146.         return true;
  147.     }
  148.    
  149.     function CheckLogin()
  150.     {
  151.          if(!isset($_SESSION)){ session_start(); }
  152.  
  153.          $sessionvar = $this->GetLoginSessionVar();
  154.          
  155.          if(empty($_SESSION[$sessionvar]))
  156.          {
  157.             return false;
  158.          }
  159.          return true;
  160.     }
  161.    
  162.     function UserFullName()
  163.     {
  164.         return isset($_SESSION['name_of_user'])?$_SESSION['name_of_user']:'';
  165.     }
  166.    
  167.     function UserEmail()
  168.     {
  169.         return isset($_SESSION['email_of_user'])?$_SESSION['email_of_user']:'';
  170.     }
  171.    
  172.     function LogOut()
  173.     {
  174.         session_start();
  175.        
  176.         $sessionvar = $this->GetLoginSessionVar();
  177.        
  178.         $_SESSION[$sessionvar]=NULL;
  179.        
  180.         unset($_SESSION[$sessionvar]);
  181.     }
  182.    
  183.     function EmailResetPasswordLink()
  184.     {
  185.         if(empty($_POST['email']))
  186.         {
  187.             $this->HandleError("Email is empty!");
  188.             return false;
  189.         }
  190.         $user_rec = array();
  191.         if(false === $this->GetUserFromEmail($_POST['email'], $user_rec))
  192.         {
  193.             return false;
  194.         }
  195.         if(false === $this->SendResetPasswordLink($user_rec))
  196.         {
  197.             return false;
  198.         }
  199.         return true;
  200.     }
  201.    
  202.     function ResetPassword()
  203.     {
  204.         if(empty($_GET['email']))
  205.         {
  206.             $this->HandleError("Email is empty!");
  207.             return false;
  208.         }
  209.         if(empty($_GET['code']))
  210.         {
  211.             $this->HandleError("reset code is empty!");
  212.             return false;
  213.         }
  214.         $email = trim($_GET['email']);
  215.         $code = trim($_GET['code']);
  216.        
  217.         if($this->GetResetPasswordCode($email) != $code)
  218.         {
  219.             $this->HandleError("Bad reset code!");
  220.             return false;
  221.         }
  222.        
  223.         $user_rec = array();
  224.         if(!$this->GetUserFromEmail($email,$user_rec))
  225.         {
  226.             return false;
  227.         }
  228.        
  229.         $new_password = $this->ResetUserPasswordInDB($user_rec);
  230.         if(false === $new_password || empty($new_password))
  231.         {
  232.             $this->HandleError("Error updating new password");
  233.             return false;
  234.         }
  235.        
  236.         if(false == $this->SendNewPassword($user_rec,$new_password))
  237.         {
  238.             $this->HandleError("Error sending new password");
  239.             return false;
  240.         }
  241.         return true;
  242.     }
  243.    
  244.     function ChangePassword()
  245.     {
  246.         if(!$this->CheckLogin())
  247.         {
  248.             $this->HandleError("Not logged in!");
  249.             return false;
  250.         }
  251.        
  252.         if(empty($_POST['oldpwd']))
  253.         {
  254.             $this->HandleError("Old password is empty!");
  255.             return false;
  256.         }
  257.         if(empty($_POST['newpwd']))
  258.         {
  259.             $this->HandleError("New password is empty!");
  260.             return false;
  261.         }
  262.        
  263.         $user_rec = array();
  264.         if(!$this->GetUserFromEmail($this->UserEmail(),$user_rec))
  265.         {
  266.             return false;
  267.         }
  268.        
  269.         $pwd = trim($_POST['oldpwd']);
  270.  
  271.         $salt = $user_rec['salt'];
  272.         $hash = $this->checkhashSSHA($salt, $pwd);
  273.        
  274.         if($user_rec['password'] != $hash)
  275.         {
  276.             $this->HandleError("The old password does not match!");
  277.             return false;
  278.         }
  279.         $newpwd = trim($_POST['newpwd']);
  280.        
  281.         if(!$this->ChangePasswordInDB($user_rec, $newpwd))
  282.         {
  283.             return false;
  284.         }
  285.         return true;
  286.     }
  287.    
  288.     //-------Public Helper functions -------------
  289.     function GetSelfScript()
  290.     {
  291.         return htmlentities($_SERVER['PHP_SELF']);
  292.     }    
  293.    
  294.     function SafeDisplay($value_name)
  295.     {
  296.         if(empty($_POST[$value_name]))
  297.         {
  298.             return'';
  299.         }
  300.         return htmlentities($_POST[$value_name]);
  301.     }
  302.    
  303.     function RedirectToURL($url)
  304.     {
  305.         header("Location: $url");
  306.         exit;
  307.     }
  308.    
  309.     function GetSpamTrapInputName()
  310.     {
  311.         return 'sp'.md5('KHGdnbvsgst'.$this->rand_key);
  312.     }
  313.    
  314.     function GetErrorMessage()
  315.     {
  316.         if(empty($this->error_message))
  317.         {
  318.             return '';
  319.         }
  320.         $errormsg = nl2br(htmlentities($this->error_message));
  321.         return $errormsg;
  322.     }    
  323.     //-------Private Helper functions-----------
  324.    
  325.     function HandleError($err)
  326.     {
  327.         $this->error_message .= $err."\r\n";
  328.     }
  329.    
  330.     function HandleDBError($err)
  331.     {
  332.         $this->HandleError($err."\r\n mysqlerror:".mysql_error());
  333.     }
  334.    
  335.     function GetFromAddress()
  336.     {
  337.         if(!empty($this->from_address))
  338.         {
  339.             return $this->from_address;
  340.         }
  341.  
  342.         $host = $_SERVER['SERVER_NAME'];
  343.  
  344.         $from ="nobody@$host";
  345.         return $from;
  346.     }
  347.    
  348.     function GetLoginSessionVar()
  349.     {
  350.         $retvar = md5($this->rand_key);
  351.         $retvar = 'usr_'.substr($retvar,0,10);
  352.         return $retvar;
  353.     }
  354.    
  355.     function CheckLoginInDB($username,$password)
  356.     {
  357.         if(!$this->DBLogin())
  358.         {
  359.             $this->HandleError("Database login failed!");
  360.             return false;
  361.         }          
  362.         $username = $this->SanitizeForSQL($username);
  363.  
  364.     $nresult = mysql_query("SELECT * FROM $this->tablename WHERE username = '$username'", $this->connection) or die(mysql_error());
  365.         // check for result
  366.         $no_of_rows = mysql_num_rows($nresult);
  367.         if ($no_of_rows > 0) {
  368.             $nresult = mysql_fetch_array($nresult);
  369.             $salt = $nresult['salt'];
  370.             $encrypted_password = $nresult['password'];
  371.             $hash = $this->checkhashSSHA($salt, $password);
  372.          
  373.            
  374.         }
  375.  
  376.  
  377.         $qry = "Select name, email from $this->tablename where username='$username' and password='$hash' and confirmcode='y'";
  378.        
  379.         $result = mysql_query($qry,$this->connection);
  380.        
  381.         if(!$result || mysql_num_rows($result) <= 0)
  382.         {
  383.             $this->HandleError("Error logging in. The username or password does not match");
  384.             return false;
  385.         }
  386.        
  387.         $row = mysql_fetch_assoc($result);
  388.        
  389.        
  390.         $_SESSION['name_of_user']  = $row['name'];
  391.         $_SESSION['email_of_user'] = $row['email'];
  392.        
  393.         return true;
  394.     }
  395.  
  396.  public function checkhashSSHA($salt, $password) {
  397.  
  398.         $hash = base64_encode(sha1($password . $salt, true) . $salt);
  399.  
  400.         return $hash;
  401.     }
  402.    
  403.     function UpdateDBRecForConfirmation(&$user_rec)
  404.     {
  405.         if(!$this->DBLogin())
  406.         {
  407.             $this->HandleError("Database login failed!");
  408.             return false;
  409.         }  
  410.         $confirmcode = $this->SanitizeForSQL($_GET['code']);
  411.        
  412.         $result = mysql_query("Select name, email from $this->tablename where confirmcode='$confirmcode'",$this->connection);  
  413.         if(!$result || mysql_num_rows($result) <= 0)
  414.         {
  415.             $this->HandleError("Wrong confirm code.");
  416.             return false;
  417.         }
  418.         $row = mysql_fetch_assoc($result);
  419.         $user_rec['name'] = $row['name'];
  420.         $user_rec['email']= $row['email'];
  421.        
  422.         $qry = "Update $this->tablename Set confirmcode='y' Where  confirmcode='$confirmcode'";
  423.        
  424.         if(!mysql_query( $qry ,$this->connection))
  425.         {
  426.             $this->HandleDBError("Error inserting data to the table\nquery:$qry");
  427.             return false;
  428.         }      
  429.         return true;
  430.     }
  431.    
  432.     function ResetUserPasswordInDB($user_rec)
  433.     {
  434.         $new_password = substr(md5(uniqid()),0,10);
  435.        
  436.         if(false == $this->ChangePasswordInDB($user_rec,$new_password))
  437.         {
  438.             return false;
  439.         }
  440.         return $new_password;
  441.     }
  442.    
  443.     function ChangePasswordInDB($user_rec, $newpwd)
  444.     {
  445.         $newpwd = $this->SanitizeForSQL($newpwd);
  446.  
  447.         $hash = $this->hashSSHA($newpwd);
  448.  
  449.     $new_password = $hash["encrypted"];
  450.  
  451.     $salt = $hash["salt"];
  452.        
  453.         $qry = "Update $this->tablename Set password='".$new_password."', salt='".$salt."' Where  id_user=".$user_rec['id_user']."";
  454.        
  455.         if(!mysql_query( $qry ,$this->connection))
  456.         {
  457.             $this->HandleDBError("Error updating the password \nquery:$qry");
  458.             return false;
  459.         }    
  460.         return true;
  461.     }
  462.    
  463.     function GetUserFromEmail($email,&$user_rec)
  464.     {
  465.         if(!$this->DBLogin())
  466.         {
  467.             $this->HandleError("Database login failed!");
  468.             return false;
  469.         }  
  470.         $email = $this->SanitizeForSQL($email);
  471.        
  472.         $result = mysql_query("Select * from $this->tablename where email='$email'",$this->connection);  
  473.  
  474.         if(!$result || mysql_num_rows($result) <= 0)
  475.         {
  476.             $this->HandleError("There is no user with email: $email");
  477.             return false;
  478.         }
  479.         $user_rec = mysql_fetch_assoc($result);
  480.  
  481.        
  482.         return true;
  483.     }
  484.    
  485.     function SendUserWelcomeEmail(&$user_rec)
  486.     {
  487.         $mailer = new PHPMailer();
  488.        
  489.         $mailer->CharSet = 'utf-8';
  490.        
  491.         $mailer->AddAddress($user_rec['email'],$user_rec['name']);
  492.        
  493.         $mailer->Subject = "Welcome to ".$this->sitename;
  494.  
  495.         $mailer->From = $this->GetFromAddress();        
  496.        
  497.         $mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n".
  498.         "Welcome! Your registration  with ".$this->sitename." is completed.\r\n".
  499.         "\r\n".
  500.         "Regards,\r\n".
  501.         "Webmaster\r\n".
  502.         $this->sitename;
  503.  
  504.         if(!$mailer->Send())
  505.         {
  506.             $this->HandleError("Failed sending user welcome email.");
  507.             return false;
  508.         }
  509.         return true;
  510.     }
  511.    
  512.     function SendAdminIntimationOnRegComplete(&$user_rec)
  513.     {
  514.         if(empty($this->admin_email))
  515.         {
  516.             return false;
  517.         }
  518.         $mailer = new PHPMailer();
  519.        
  520.         $mailer->CharSet = 'utf-8';
  521.        
  522.         $mailer->AddAddress($this->admin_email);
  523.        
  524.         $mailer->Subject = "Registration Completed: ".$user_rec['name'];
  525.  
  526.         $mailer->From = $this->GetFromAddress();        
  527.        
  528.         $mailer->Body ="A new user registered at ".$this->sitename."\r\n".
  529.         "Name: ".$user_rec['name']."\r\n".
  530.         "Email address: ".$user_rec['email']."\r\n";
  531.        
  532.         if(!$mailer->Send())
  533.         {
  534.             return false;
  535.         }
  536.         return true;
  537.     }
  538.    
  539.     function GetResetPasswordCode($email)
  540.     {
  541.        return substr(md5($email.$this->sitename.$this->rand_key),0,10);
  542.     }
  543.    
  544.     function SendResetPasswordLink($user_rec)
  545.     {
  546.         $email = $user_rec['email'];
  547.        
  548.         $mailer = new PHPMailer();
  549.        
  550.         $mailer->CharSet = 'utf-8';
  551.        
  552.         $mailer->AddAddress($email,$user_rec['name']);
  553.        
  554.         $mailer->Subject = "Your reset password request at ".$this->sitename;
  555.  
  556.         $mailer->From = $this->GetFromAddress();
  557.        
  558.         $link = $this->GetAbsoluteURLFolder().
  559.                 '/resetpwd.php?email='.
  560.                 urlencode($email).'&code='.
  561.                 urlencode($this->GetResetPasswordCode($email));
  562.  
  563.         $mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n".
  564.         "There was a request to reset your password at ".$this->sitename."\r\n".
  565.         "Please click the link below to complete the request: \r\n".$link."\r\n".
  566.         "Regards,\r\n".
  567.         "Webmaster\r\n".
  568.         $this->sitename;
  569.        
  570.         if(!$mailer->Send())
  571.         {
  572.             return false;
  573.         }
  574.         return true;
  575.     }
  576.    
  577.     function SendNewPassword($user_rec, $new_password)
  578.     {
  579.         $email = $user_rec['email'];
  580.        
  581.         $mailer = new PHPMailer();
  582.        
  583.         $mailer->CharSet = 'utf-8';
  584.        
  585.         $mailer->AddAddress($email,$user_rec['name']);
  586.        
  587.         $mailer->Subject = "Your new password for ".$this->sitename;
  588.  
  589.         $mailer->From = $this->GetFromAddress();
  590.        
  591.         $mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n".
  592.         "Your password is reset successfully. ".
  593.         "Here is your updated login:\r\n".
  594.         "username:".$user_rec['username']."\r\n".
  595.         "password:$new_password\r\n".
  596.         "\r\n".
  597.         "Login here: ".$this->GetAbsoluteURLFolder()."/login.php\r\n".
  598.         "\r\n".
  599.         "Regards,\r\n".
  600.         "Webmaster\r\n".
  601.         $this->sitename;
  602.        
  603.         if(!$mailer->Send())
  604.         {
  605.             return false;
  606.         }
  607.         return true;
  608.     }    
  609.    
  610.     function ValidateRegistrationSubmission()
  611.     {
  612.         //This is a hidden input field. Humans won't fill this field.
  613.         if(!empty($_POST[$this->GetSpamTrapInputName()]) )
  614.         {
  615.             //The proper error is not given intentionally
  616.             $this->HandleError("Automated submission prevention: case 2 failed");
  617.             return false;
  618.         }
  619.        
  620.         $validator = new FormValidator();
  621.         $validator->addValidation("name","req","Please fill in Name");
  622.         $validator->addValidation("email","email","The input for Email should be a valid email value");
  623.         $validator->addValidation("email","req","Please fill in Email");
  624.  
  625.         $validator->addValidation("password","req","Please fill in Password");
  626.  
  627.        
  628.         if(!$validator->ValidateForm())
  629.         {
  630.             $error='';
  631.             $error_hash = $validator->GetErrors();
  632.             foreach($error_hash as $inpname => $inp_err)
  633.             {
  634.                 $error .= $inpname.':'.$inp_err."\n";
  635.             }
  636.             $this->HandleError($error);
  637.             return false;
  638.         }        
  639.         return true;
  640.     }
  641.    
  642.     function CollectRegistrationSubmission(&$formvars)
  643.     {
  644.         $formvars['name'] = $this->Sanitize($_POST['name']);
  645.     $formvars['username'] = $this->Sanitize($_POST['username']);
  646.         $formvars['email'] = $this->Sanitize($_POST['email']);
  647.         $formvars['password'] = $this->Sanitize($_POST['password']);
  648.    
  649.     }
  650.    
  651.     function SendUserConfirmationEmail(&$formvars)
  652.     {
  653.         $mailer = new PHPMailer();
  654.        
  655.         $mailer->CharSet = 'utf-8';
  656.        
  657.         $mailer->AddAddress($formvars['email'],$formvars['name']);
  658.        
  659.         $mailer->Subject = "Your registration with ".$this->sitename;
  660.  
  661.         $mailer->From = $this->GetFromAddress();        
  662.        
  663.         $confirmcode = $formvars['confirmcode'];
  664.        
  665.         $confirm_url = $this->GetAbsoluteURLFolder().'/confirmreg.php?code='.$confirmcode;
  666.        
  667.         $mailer->Body ="Hello ".$formvars['name']."\r\n\r\n".
  668.         "Thanks for your registration with ".$this->sitename."\r\n".
  669.         "Please click the link below to confirm your registration.\r\n".
  670.         "$confirm_url\r\n".
  671.         "\r\n".
  672.         "Regards,\r\n".
  673.         "Webmaster\r\n".
  674.         $this->sitename;
  675.  
  676.         if(!$mailer->Send())
  677.         {
  678.             $this->HandleError("Failed sending registration confirmation email.");
  679.             return false;
  680.         }
  681.         return true;
  682.     }
  683.     function GetAbsoluteURLFolder()
  684.     {
  685.         $scriptFolder = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';
  686.  
  687.         $urldir ='';
  688.         $pos = strrpos($_SERVER['REQUEST_URI'],'/');
  689.         if(false !==$pos)
  690.         {
  691.             $urldir = substr($_SERVER['REQUEST_URI'],0,$pos);
  692.         }
  693.  
  694.         $scriptFolder .= $_SERVER['HTTP_HOST'].$urldir;
  695.  
  696.         return $scriptFolder;
  697.     }
  698.    
  699.     function SendAdminIntimationEmail(&$formvars)
  700.     {
  701.         if(empty($this->admin_email))
  702.         {
  703.             return false;
  704.         }
  705.         $mailer = new PHPMailer();
  706.        
  707.         $mailer->CharSet = 'utf-8';
  708.        
  709.         $mailer->AddAddress($this->admin_email);
  710.        
  711.         $mailer->Subject = "New registration: ".$formvars['name'];
  712.  
  713.         $mailer->From = $this->GetFromAddress();        
  714.        
  715.         $mailer->Body ="A new user registered at ".$this->sitename."\r\n".
  716.         "Name: ".$formvars['name']."\r\n".
  717.         "Email address: ".$formvars['email']."\r\n".
  718.         "UserName: ".$formvars['username'];
  719.        
  720.         if(!$mailer->Send())
  721.         {
  722.             return false;
  723.         }
  724.         return true;
  725.     }
  726.    
  727.     function SaveToDatabase(&$formvars)
  728.     {
  729.         if(!$this->DBLogin())
  730.         {
  731.             $this->HandleError("Database login failed!");
  732.             return false;
  733.         }
  734.         if(!$this->Ensuretable())
  735.         {
  736.             return false;
  737.         }
  738.         if(!$this->IsFieldUnique($formvars,'email'))
  739.         {
  740.             $this->HandleError("This email is already registered");
  741.             return false;
  742.         }
  743.        
  744.     if(!$this->IsFieldUnique($formvars,'username'))
  745.         {
  746.             $this->HandleError("This UserName is already used. Please try another username");
  747.             return false;
  748.         }
  749.              
  750.         if(!$this->InsertIntoDB($formvars))
  751.         {
  752.             $this->HandleError("Inserting to Database failed!");
  753.             return false;
  754.         }
  755.         return true;
  756.     }
  757.    
  758.     function IsFieldUnique($formvars,$fieldname)
  759.     {
  760.         $field_val = $this->SanitizeForSQL($formvars[$fieldname]);
  761.         $qry = "select username from $this->tablename where $fieldname='".$field_val."'";
  762.         $result = mysql_query($qry,$this->connection);  
  763.         if($result && mysql_num_rows($result) > 0)
  764.         {
  765.             return false;
  766.         }
  767.         return true;
  768.     }
  769.    
  770.     function DBLogin()
  771.     {
  772.  
  773.         $this->connection = mysqli_connect($this->db_host,$this->username,$this->pwd);
  774.  
  775.         if(!$this->connection)
  776.         {  
  777.             $this->HandleDBError("Database Login failed! Please make sure that the DB login credentials provided are correct");
  778.             return false;
  779.         }
  780.         if(!mysqli_select_db($this->connection, $this->database ))
  781.         {
  782.             $this->HandleDBError('Failed to select database: '.$this->database.' Please make sure that the database name provided is correct');
  783.             return false;
  784.         }
  785.         if(!mysqli_query($this->connection, "SET NAMES 'UTF8'"))
  786.         {
  787.             $this->HandleDBError('Error setting utf8 encoding');
  788.             return false;
  789.         }
  790.         return true;
  791.     }    
  792.    
  793.     function Ensuretable()
  794.     {
  795.         $result = mysqli_query($this->tablename, "SHOW COLUMNS FROM");  
  796.         if(!$result || mysql_num_rows($result) <= 0)
  797.         {
  798.             return $this->CreateTable();
  799.         }
  800.         return true;
  801.     }
  802.    
  803.     function CreateTable()                                            
  804.     {
  805.        
  806.         $qry = "Create Table $this->tablename (".
  807.                 "id_user INT NOT NULL AUTO_INCREMENT ,".
  808.                 "name VARCHAR( 128 ) NOT NULL ,".
  809.                 "email VARCHAR( 64 ) NOT NULL ,".
  810.                 "phone_number VARCHAR( 16 ) NOT NULL ,".
  811.                 "username VARCHAR( 16 ) NOT NULL ,".
  812.         "salt VARCHAR( 50 ) NOT NULL ,".
  813.                 "password VARCHAR( 80 ) NOT NULL ,".
  814.                 "confirmcode VARCHAR(32) ,".
  815.                 "PRIMARY KEY ( id_user )".
  816.                 ")";
  817.    
  818.                
  819.         if(!mysqli_query($qry,$this->connection))
  820.         {
  821.             $this->HandleDBError("Error creating the table \nquery was\n $qry");
  822.             return false;
  823.         }
  824.         return true;
  825.     }
  826.    
  827.     function InsertIntoDB(&$formvars)
  828.     {
  829.    
  830.         $confirmcode = $this->MakeConfirmationMd5($formvars['email']);
  831.  
  832.         $formvars['confirmcode'] = $confirmcode;
  833.  
  834.     $hash = $this->hashSSHA($formvars['password']);
  835.  
  836.     $encrypted_password = $hash["encrypted"];
  837.        
  838.  
  839.  
  840.     $salt = $hash["salt"];
  841.        
  842.      
  843.  
  844.  
  845.         $insert_query = 'insert into '.$this->tablename.'(
  846.         name,
  847.         email,
  848.         username,  
  849.         password,
  850.         salt,
  851.         confirmcode
  852.         )
  853.         values
  854.         (
  855.         "' . $this->SanitizeForSQL($formvars['name']) . '",
  856.         "' . $this->SanitizeForSQL($formvars['email']) . '",
  857.         "' . $this->SanitizeForSQL($formvars['username']) . '",
  858.         "' . $encrypted_password . '",
  859.         "' . $salt . '",
  860.         "' . $confirmcode . '"
  861.         )';  
  862.  
  863.  
  864.         if(!mysql_query( $insert_query ,$this->connection))
  865.         {
  866.             $this->HandleDBError("Error inserting data to the table\nquery:$insert_query");
  867.             return false;
  868.         }        
  869.         return true;
  870.     }
  871.     function hashSSHA($password) {
  872.  
  873.         $salt = sha1(rand());
  874.         $salt = substr($salt, 0, 10);
  875.         $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
  876.         $hash = array("salt" => $salt, "encrypted" => $encrypted);
  877.         return $hash;
  878.     }
  879.     function MakeConfirmationMd5($email)
  880.     {
  881.         $randno1 = rand();
  882.         $randno2 = rand();
  883.         return md5($email.$this->rand_key.$randno1.''.$randno2);
  884.     }
  885.     function SanitizeForSQL($str)
  886.     {
  887.         if( function_exists( "mysql_real_escape_string" ) )
  888.         {
  889.               $ret_str = mysql_real_escape_string( $str );
  890.         }
  891.         else
  892.         {
  893.               $ret_str = addslashes( $str );
  894.         }
  895.         return $ret_str;
  896.     }
  897.    
  898.  /*
  899.     Sanitize() function removes any potential threat from the
  900.     data submitted. Prevents email injections or any other hacker attempts.
  901.     if $remove_nl is true, newline chracters are removed from the input.
  902.     */
  903.     function Sanitize($str,$remove_nl=true)
  904.     {
  905.         $str = $this->StripSlashes($str);
  906.  
  907.         if($remove_nl)
  908.         {
  909.             $injections = array('/(\n+)/i',
  910.                 '/(\r+)/i',
  911.                 '/(\t+)/i',
  912.                 '/(%0A+)/i',
  913.                 '/(%0D+)/i',
  914.                 '/(%08+)/i',
  915.                 '/(%09+)/i'
  916.                 );
  917.             $str = preg_replace($injections,'',$str);
  918.         }
  919.  
  920.         return $str;
  921.     }    
  922.     function StripSlashes($str)
  923.     {
  924.         if(get_magic_quotes_gpc())
  925.         {
  926.             $str = stripslashes($str);
  927.         }
  928.         return $str;
  929.     }    
  930. }
  931. ?>
Add Comment
Please, Sign In to add comment