Home > php > OPP Sign In/Out procedure in PHP

OPP Sign In/Out procedure in PHP

December 9Hits:4


As a self-taught student of Web-Development and Web Technologies, I created a simple sign in/out form in PHP, just for practice purposes and some fun!

I read the O'reilly's book about PHP and I found one sentence there ( I really don't remember where it was though):

A novice web developer will program procedurally, but an advance one, will know that everything need to be handle as an object.

So it is. I never done an OOP programing before and I though that this will be an excellence motive to do so. In parallel I study about MVC model and I wanted to be sure that I have understand the OOP programming, so it can be used for MVC apps. Is my code clean, well writen to support a big scale app? What changes do I have to make?

The Classes

I developed two classes. One called Main and it used for procedures that need to be used in the hole app, like connected to DB, get user info and error handling procedures. The other called UserAuth holds the Login/Register/Logout methods as well as some other ones.

In the next paragraph I post the code from an index.php test page, and the other two files that hold the Main and UserAuth classes respectively.

The files


<?php      session_start();     require_once 'userAuth.class.php';      $USER = new userAuth();      # Check login state     if( $USER->isLogin()) {         echo $USER->showEmail();     }       # Login     if (isset($_POST['login-button'])) {         $login = $USER->Login($_POST['Lemail'], $_POST['LPass']);         if ($login['State'] == true) {             echo $USER->showEmail();         }         else {             echo $login['Msg'];         }     }      # Register     if (isset($_POST['register-button'])) {         $register = $USER->Register($_POST['Remail'], $_POST['RPass1'], $_POST['RPass2'], $_POST['g-recaptcha-response']);         if ($register['State'] == true) {             echo "We have register your email to our databases.";         }         else {             echo $register['Msg'];         }     }      # Logout     if (isset($_POST['logout-button'])) {         $USER->Logout();     } ?>  <!DOCTYPE html> <html> <head>     <title>Simple Sign In/Out</title> </head> <body>     <form id="login" method="POST">              <input id="Lemail" name="Lemail" placeholder="Email" required="required" type="email" autocomplete="off">         <input id="LPass" name="LPass" placeholder="Password" required="required" type="password" autocomplete="off">         <button type="submit" id="login-button" name="login-button">Dive</button>      </form>      <form id="register" method="POST">         <input id="Remail" name="Remail" placeholder="[email protected]" required="required" type="text" autocomplete="off" >         <input id="RPass1" name="RPass1" placeholder="Your Password" required="required" type="password" autocomplete="off">         <input id="RPass2" name="RPass2" placeholder="Your Password" required="required" type="password" autocomplete="off">              <button type="submit" id="register-button" name="register-button">Register</button>     </form>      <form id="logout" method="POST">         <button id="logout-button" name="logout-button">Logout</button>     </form> </body> </html> 


<?php     require_once 'main.class.php';     require_once '../lib/bcrypt.php';      class userAuth extends Main     {          private $L_UserEmail    =   NULL;         private $L_UserPass     =   NULL;          private $R_UserEmail    =   NULL;         private $R_UserPass1    =   NULL;         private $R_UserPass2    =   NULL;         private $ReCaptcha      =   NULL;           public function showEmail() {             return $this->getUserEmail();         }          public function isLogin() {             if($this->UserIsLogin()) {                 return true;             }             else {                 return false;             }         }           private function UserIsLogin() {             if (isset($_SESSION['login'])) {                 return true;             }             else {                 return false;             }         }           public function Login($UserEmail, $UserPass) {             $this->L_UserEmail = $UserEmail;             $this->L_UserPass = $UserPass;              if (!$this->exist_LoginEmail()) {                 return $this->setReturnState('User email does not exist in our databases.');             }              if (!$this->correct_LoginPass()) {                 return $this->setReturnState('Password is wrong.');             }              return $this->doLogin();          }          public function Logout(/*$emails*/) {             $this->clearUserEmail();             session_destroy();         }          public function Register($UserEmail, $UserPass1, $UserPass2, $ReCaptcha) {             $this->R_UserEmail = $UserEmail;             $this->R_UserPass1 = $UserPass1;             $this->R_UserPass2 = $UserPass2;             $this->ReCaptcha = $ReCaptcha;               /*if (!$this->valid_Captcha()) {                 return $this->setReturnState('Please verify yourself as human.');             }*/              if (!$this->valid_RegisterEmail()) {                 return $this->setReturnState('Only letters and nubers are allowed for email. Please see <a href="#">security</a> for more details.');             }              if (!$this->valid_RegisterPass()) {                 return $this->setReturnState('Passwords do not match.');             }              if ($this->exist_RegisterEmail()) {                 return $this->setReturnState('Email already registered.');             }              return $this->doRegister();          }            private function exist_LoginEmail() {             try {                 $STH = $this->DHB->prepare("SELECT UserEmail FROM Users WHERE UserEmail = :user_email");                 $STH->bindParam(':user_email', $this->L_UserEmail);                 $STH->execute();                  # Get the user info                 $row = $STH->fetchAll();                  # Check if username exist                 if (!$row) {                     return false;                 }                  else {                     return true;                 }             }             catch(PDOException $e) {                 file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);                 return false;             }         }          private function correct_LoginPass() {             try {                 $STH = $this->DHB->prepare("SELECT UserPass FROM Users WHERE UserEmail = :user_email");                 $STH->bindParam(':user_email', $this->L_UserEmail);                 $STH->execute();                  # Get the user info                 $row = $STH->fetchAll();                  $isGood = password_verify($this->L_UserPass, $row[0]['UserPass']);                  # Check if password is good                 if ($isGood) {                     return true;                 }                 else {                     return false;                 }             }             catch(PDOException $e) {                 file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);                 return false;             }         }          private function valid_Captcha() {             # FIRST WE CHECK IF THE FORM WAS POSTED BY A HUMAN             if ($this->ReCaptcha == NULL) {                 return false;             }              # HAS THE USER BEEN AUTHORIAZED BY GOOGLE ?             $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6Lc6mxcTAAAAAABnITaUtxp3pbH_xUf8fEtj_f7p&response=".$this->ReCaptcha."&remoteip=".$_SERVER['REMOTE_ADDR']);             if($response.success == false) {                 return false;             }              return true;         }          private function valid_RegisterEmail() {             # CHECK IF EMAIL CONSISTS ONLY a-z A-Z 0-9 characters             if (!ctype_alnum($this->R_UserEmail)) {                 return false;             }              return true;         }          private function valid_RegisterPass() {             if ($this->R_UserPass1 == $this->R_UserPass2) {                 return true;             }              return false;         }          private function exist_RegisterEmail() {             $this->R_UserEmail .= [email protected]';             try {                 # STH means "Statement Handle"                 $STH = $this->DHB->prepare("SELECT * FROM Users WHERE UserEmail = :user_email");                 $STH->bindParam(':user_email', $this->R_UserEmail);                 $STH->execute();                  if($STH->rowCount() <= 0) {  # Check if username is already registered                     # Email has not registered yet                     return false;                 }                  return true;              }             catch(PDOException $e) {                 file_put_contents('../lib/PDOErrors.txt', $e->getMessage(), FILE_APPEND);                 return false;             }         }          private function doRegister() {             $hashedPassword = password_hash($this->R_UserPass1, PASSWORD_BCRYPT, array("cost" => 13));                              $STH = $this->DHB->prepare("INSERT INTO Users(UserEmail, UserPass) values(:user_email, :user_pass)");             $STH->bindParam(':user_email', $this->R_UserEmail);             $STH->bindParam(':user_pass', $hashedPassword);             $STH->execute();               if (!$STH) {                 return $this->setReturnState('We could not process your order. Please try again later.');             }              return $this->setReturnState(null, true);         }          private function doLogin() {             $this->setUserEmail($this->L_UserEmail);             return $this->setReturnState(null, true);         }          private function setUserEmail($email) {             $_SESSION['login'] = $email;         }          private function clearUserEmail() {             unset($_SESSION['login']);          }      }   # End of User Auth Class ?> 


<?php       # The symbolic constants of databse connection     require_once '../lib/config.php';      class Main     {         protected $DHB  =   NULL;          function __construct()         {             try {                 # DHB : Database Handle                 $this->DHB = new PDO("mysql:host=".DB_HOST.";dbname=".DB_DATABSE, DB_USER, DB_PASSWORD);                 $this->DHB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );             }             catch(PDOException $e) {                 file_put_contents('../PDOErrors.txt', $e->getMessage(), FILE_APPEND);             }         }          protected function getUserEmail() {             return $_SESSION['login'];         }          protected function setReturnState($msg, $state = false) {             return array('State' => $state, 'Msg' => $msg);         }      } ?> 

Thank you for your time! :)

Tags:php, oop, php5, mvc

Related Articles

  • OPP Sign In/Out procedure in PHPDecember 9

    Preface As a self-taught student of Web-Development and Web Technologies, I created a simple sign in/out form in PHP, just for practice purposes and some fun! I read the O'reilly's book about PHP and I found one sentence there ( I really don't rememb

  • Issues with module signing and SSIS catalog internal proceduresOctober 17

    I'm trying to set up a stored procedure to execute an SSIS package. I want to allow a user to execute only this stored procedure, so I need it to run as a different user. I found this article which detailed creating a certificate and signing the modu

  • Find signed procedures, functions, triggers, assemblies and by which certificates / asymmetric keysJanuary 22

    I have created a few Certificates (via CREATE CERTIFICATE) and Asymmetric Keys (via CREATE ASYMMETRIC KEY) and used them to sign and counter-sign various Stored Procedures, User-Defined Functions (UDFs), Triggers, and Assemblies (via ADD SIGNATURE).

  • Calling sp_start_job from a stored procedureJune 25

    Our developers need to be able to start a SQL Server Agent job from their .Net code. I know I can call msdb..sp_start_job to do just that, but I don't want to give general user accounts direct access to run jobs. What I'd like to do is to create a st

  • How can I give a SQL Server user permission to run one stored procedure and nothing else?November 6

    I need to be able to remotely monitor the disk space on a SQL 2005 server. To do this I need to give a sql server user the ability to run the following stored procedure: EXEC xp_fixeddrives; Ideally this user wouldn't have permission to run other sto

  • Server permissions of an activation stored procedure of a Server Broker queueMay 21

    I have a stored procedure that queries the sys.dm_exec_requests view. In the stored procedure the view only returns one row, while the stored procedure needs to see all of them. The MSDN article on the view says that what is returned depends on the u

  • Launching SQL Agent Job from stored procedure not on [msdb] database, or, How Necessary is SET TRUSTWORTHY ON?April 24

    (With apologies in advance since I've been asked to pick up a project written by someone with more skills than me but who I can no longer ping for questions. If it sounds like I may be using terminology inelegantly, it's because I probably don't know

  • How can I restore a database such that I can use it on a server where I don't have the security admin roleJune 22

    On a SQL 2008 instance, I have a login with the dbcreator and public roles. When I restore a database onto this server, I am then unable to use that database because all the user -> login mappings in it are broken (the ids are different on different

  • Accessing Service Broker from Different DatabasesDecember 2

    In my Application we have a lot of databases nearly 100 dbs. We are planning to use Service Broker for calling a Stored Proc Async. Instead of running Service Broker on all the Databases, Is it possible to run the Service Broker on only one Database

  • Implementing Paillier Signature Scheme in DelphiMarch 31

    I've been trying to implement the Paillier Signature Scheme in Delphi, but I can't get it to work and I don't know where the problem is. First of all, I got my info about the scheme from this paper. The signature scheme is on page 9. The problem is t

  • Schemas and user rightsJune 27

    I have 2 schemas, lets say sch1 and sch2. Each owned by different user. I do want to grant SELECT rights on sch2.MyTable (but just this one object) to sch1 procedures/views AND allow to reference sch2.MyTable in sch1 foreign key constraints. I do NOT

  • User Mapped to a certificate in SQLFebruary 21

    I need to create a user ,who can log on to a contained DB.In this context what is the benefit of using a user mapped to a certificate? --------------Solutions------------- The benefit of users mapped to a certificate is to use certificate signatures

  • Create a certificate with a private keyApril 11

    Reading this answer I have a question about it: How can I create a certificate with a private key in my app database? --------------Solutions------------- CREATE CERTIFICATE, see the first example Creating a self-signed certificate: use <mydb>; go C

  • How to measure or find cost of creating a query plan?

    How to measure or find cost of creating a query plan?December 29

    I have a typical case where parameter sniffing causes a "bad" execution plan to land in the plan cache, causing subsequent executions of my stored procedure to be very slow. I can "solve" this problem with local variables, OPTIMIZE FOR

  • Composite Primary Key in multi-tenant SQL Server databaseApril 17

    I'm building a multi-tenant app (single database, single schema) using ASP Web API, Entity Framework, and SQL Server/Azure database. This app will be used by 1000-5000 customers. All the tables will have TenantId (Guid / UNIQUEIDENTIFIER) field. Righ

  • Self-signing client certificates and distributing them, is the following a sound procedure?August 8

    I have a case at hand as follows: There is a number of clients in Internet (i.e. untrusted channel), initially in hundreds but growing in numbers. There is a server doing processing related to these clients. This relation is established prior to this

  • SSDT Schema Comparison for Stored Procedure signed by a CertificateDecember 7

    I am using SSDT 14.0.50730.0 in Visual Studio Professional 2015. I am comparing databases between two instances and it is finding that there are stored procedures that do not match with regard to their signatures. In both instances, the Certificate w

  • oracle PL/SQL function/procedure call with &-sign prefixed parametersFebruary 17

    I came across PL/SQL function/procedure calls with &-sign prefixed parameters, for example m_package.DeleteDuplicates(&param1, &parma2) . Can someone tell me what does this & prefix imply. --------------Solutions------------- Hello "&

  • staying not signed in: is it the safest procedure?January 29

    each time I do connect to a private or public network I log into websites by keeping the option "stay signed in" or "keep me signed in" unselected, so I have to re-type my username and passwod as often as I reopen the browser and want

  • What are the benefits of a self signed certificate on a live site?April 30

    Are there any benefits of a self signed certificate on a live site? I know in IIS 7 you have the ability to self sign a certificate and I was wondering if using that as a precurser to buying one from a CA would be a good idea. Do you get the same enc

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.354 s.