- Login and Register Script In PHP PDO With MySQL
- Table Content
- 1. Project Configuration
- 2. Database and Table Making
- 3. connection.php
- 4. Password Hashed / Encrypt Guidelines
- 5. index.php [ login form ]
- 5.1 PHP Login Code With PDO
- 5.2 Login Code Logic Explanation
- 6. register.php [ registration form ]
- 6.1 PHP Registration Code With PDO
- 6.2 Registration Code Logic Explanation
- 7. welcome.php
- 7.1 Welcome Page Code Logic Explanation
- 8. logout.php
- 1. Project Configuration
- 2. Database And Table Making
- 3. connection.php
- 4. Password Hashed / Encrypt Guidelines
- 5. index.php [ login form ]
- 5.1 PHP Login Code With PDO
- 5.2 Login Code Logic Explanation :
- 6. register.php [ registeration form ]
- 6.1 PHP Registration Code With PDO
- 6.2 Registration Codes Logic Explanation :
- 7. welcome.php
- 7.1 Welcome Page Codes Logic Explanation :
- 8. logout.php
- MySQL пароль () функция для PHP
Login and Register Script In PHP PDO With MySQL
Hi, welcome back guys, in the previous tutorial, I discussed codes for PHP CRUD operations with PDO. Now I’m going to explaining Login and Register Script in PHP PDO with MySQL Database in this tutorial.
In this project, I use the PHP password hashing function to create the password encryption unit. The password hashing function builds up in PHP 5.5 edition and includes in PHP 7 edition which has become widely used to construct secure encrypted passwords in your dynamic PHP web project.
The second most valuable element that I add in this project the user login access facility with the session object. Its unique information to save users.
Well, I’m working on how to create encrypted passwords on the login page, and how to check encrypted passwords. And how to retain exclusive access to user logins with session objects and encrypted passwords. I hope this registration and login script will benefit your project.
Table Content
1. Project Configuration
2. Database and Table Making
3. connection.php
4. Password Hashed / Encrypt Guidelines
5. index.php [ login form ]
5.1 PHP Login Code With PDO
5.2 Login Code Logic Explanation
6. register.php [ registration form ]
6.1 PHP Registration Code With PDO
6.2 Registration Code Logic Explanation
7. welcome.php
7.1 Welcome Page Code Logic Explanation
8. logout.php
1. Project Configuration
I assume the XAMPP server is installed on your system. Look for path of project C:\xampp\htdocs\Login-Register-PHP-PDO.
I installed the XAMPP server in C: drive here and I set up this project inside this drive. But you can set up your specific drive you want XAMPP server installed.
2. Database And Table Making
CREATE DATABASE php_pdo_login_db; CREATE TABLE `tbl_user` ( `user_id` int(11) NOT NULL, `username` varchar(15) NOT NULL, `email` varchar(40) NOT NULL, `password` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
3. connection.php
Since creating a database and table, we continue to create a new file named ‘connection.php’ that includes database connection code for error managing within the try/catch block.
;dbname=",$db_user,$db_password); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); > catch(PDOEXCEPTION $e) < $e->getMessage(); > ?>
4. Password Hashed / Encrypt Guidelines
The entire project hash password by password_hash() function. See the first parameter $password that includes a straightforward 123456 password and the second parameter PASSWORD_DEFAULT used to describe the hash password algorithm.
Using the password_verify() function to verify password string with match hashed/encrypted password string after it is true and false.
5. index.php [ login form ]
Index.php as the login form that takes username/email and password to the welcome page for users to enter. If any error and success messages appeared in login codes apart from variables $errorMsg and $loginMsg displaying suitable custom messages.
5.1 PHP Login Code With PDO
Identifying the specific user name or email and encrypted password from the database table is the responsibility for these codes. If both values are detected in the table then a session will begin and enable the user to enter the welcome page, otherwise, the relevant message will be displayed.
if(isset($_REQUEST['btn_login'])) //button name is "btn_login" < $username =strip_tags($_REQUEST["txt_username_email"]); //textbox name "txt_username_email" $email =strip_tags($_REQUEST["txt_username_email"]); //textbox name "txt_username_email" $password =strip_tags($_REQUEST["txt_password"]); //textbox name "txt_password" if(empty($username))< $errorMsg[]="please enter username or email"; //check "username/email" textbox not empty >else if(empty($email)) < $errorMsg[]="please enter username or email"; //check "username/email" textbox not empty >else if(empty($password)) < $errorMsg[]="please enter password"; //check "passowrd" textbox not empty >else < try < $select_stmt=$db->prepare("SELECT * FROM tbl_user WHERE username=:uname OR email=:uemail"); //sql select query $select_stmt->execute(array(':uname'=>$username, ':uemail'=>$email)); //execute query with bind parameter $row=$select_stmt->fetch(PDO::FETCH_ASSOC); if($select_stmt->rowCount() > 0) //check condition database record greater zero after continue < if($username==$row["username"] OR $email==$row["email"]) //check condition user taypable "username or email" are both match from database "username or email" after continue < if(password_verify($password, $row["password"])) //check condition user taypable "password" are match from database "password" using password_verify() after continue < $_SESSION["user_login"] = $row["user_id"]; //session name is "user_login" $loginMsg = "Successfully Login. "; //user login success message header("refresh:2; welcome.php"); //refresh 2 second after redirect to "welcome.php" page >else < $errorMsg[]="wrong password"; >> else < $errorMsg[]="wrong username or email"; >> else < $errorMsg[]="wrong username or email"; >> catch(PDOException $e) < $e->getMessage(); > > > ?>
5.2 Login Code Logic Explanation :
Row no 3 – Use function require_once to include connection.php database connection file. Its file object is the $db help to select the user login access query to execute SQL.
Row no 5 – Start the session with the session_start() function by logging in to the session object by the user.
Row no 7 to 10 – if condition finds the ‘user_login’ session object if it was found to send header() function to the welcome page. Because session base login users can not access the login page directly, they are required to log out from the welcome page.
Row no 12 – Use the $_REQUEST [ ] method array to get the btn_login attribute value of the login form button. The isset() function set up this attribute value click event.
Row no 14 to 16 – The $_REQUEST[ ] array method that gets txt_username_email and txt_password values from the name of the text box attribute in the login form. And they’ll be assigning $username, $email and $password to created new variables.
Row no 18 to 26 – if and else condition, the empty() function checks that all text box variable values are not empty.
Row no 28 to 33 – Within else condition open try/catch block. apply the select PDO query in the prepare() statement and select all records.
The array() function binds the value of the variables :uname and :uemail in selected query placed within the execute() function. The $username and $email variables keep those values.
PDOStatement:: fetch method returns a row from the result set. PDO:: FETCH_ASSOC parameter informs PDO to return array value indexed by table column username and email. The $row is an array.
Row no 35 – The number of rows returnable by rowCount() function is greater than zero (> 0) if condition check returns.
Row no 37 – if condition, using = = operator check to match the user-typed form field username and email values from the table.
The username and email values of both the text box hold $username, $email variables. And retrieve able table fields of username and email both values hold by $row array variable.
Row no 39 to 44 – If condition, the function password_verify () checks the value of the password text box match from the hashed record of the table password.
The password text box value keeps the variable $password and retrieve able table filed of password value keep by $row variable.
Above all conditions are true then the session will start paste user_login session object in $_SESSION [] array and assign it to the table id. Apply the successful login message and the header() function will keep this message within 2 seconds, it will be sent in the welcome page.
Note – I do not discuss any else condition in login codes that any else condition will display a particular error message when login codes are triggered. And that error message assign into $errorMsg[] array variable.
Related Tutorials:-
6. register.php [ registeration form ]
This page contains a registration form with three input box username, email, and password for registering new users data into the database.
If any message of success and error detects in the registration code then the variable $errorMsg and $registerMsg display the appropriate message.
6.1 PHP Registration Code With PDO
See PHP registration codes below for registering new user data in the database. These codes are also responsible for checking duplicate usernames or email from the database while signing in if any duplicate found then its display error message sorry email or username already exists.
else if(empty($email)) < $errorMsg[]="Please enter email"; //check email textbox not empty >else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) < $errorMsg[]="Please enter a valid email address"; //check proper email format >else if(empty($password)) < $errorMsg[]="Please enter password"; //check passowrd textbox not empty >else if(strlen($password) < 6)< $errorMsg[] = "Password must be atleast 6 characters"; //check passowrd must be 6 characters >else < try < $select_stmt=$db->prepare("SELECT username, email FROM tbl_user WHERE username=:uname OR email=:uemail"); // sql select query $select_stmt->execute(array(':uname'=>$username, ':uemail'=>$email)); //execute query $row=$select_stmt->fetch(PDO::FETCH_ASSOC); if($row["username"]==$username) < $errorMsg[]="Sorry username already exists"; //check condition username already exists >else if($row["email"]==$email) < $errorMsg[]="Sorry email already exists"; //check condition email already exists >else if(!isset($errorMsg)) //check no "$errorMsg" show then continue < $new_password = password_hash($password, PASSWORD_DEFAULT); //encrypt password using password_hash() $insert_stmt=$db->prepare("INSERT INTO tbl_user (username,email,password) VALUES (:uname,:uemail,:upassword)"); //sql insert query if($insert_stmt->execute(array( ':uname' =>$username, ':uemail'=>$email, ':upassword'=>$new_password))) < $registerMsg="Register Successfully. Please Click On Login Account Link"; //execute query success message >> > catch(PDOException $e) < echo $e->getMessage(); > > > ?>
6.2 Registration Codes Logic Explanation :
Row no 3 – Use the require_once function adds the connection file to the database. Using database object $db to fire PDO queries.
Row no 5 – Using the $_REQUEST[ ] array method we get attribute value btn_register for the registration form button name. And this attribute value clicks event targeting by the isset() function.
Row no 7 to 9 – Using $_REQUEST[ ] array method gets all values of txt_username, txt_email, and txt_password by name attribute in the registration form fields.
Row no 11 to 25 – If and else condition check form fields all values not null using the function empty(). As well as checking correct email address format and password length minimum of 6 characters must be required.
FILTER_VALIDATE_EMAIL – The FILTER_VALIDATE_EMAIL filter validates an e-mail address ( according to php.net ).
Within try/catch block apply PDO select query under in prepare() statement and select the username and email value from the table.
Inside the execute() function the array() function bind the value of the variables :uname and :uemail in query location. The $username and $email variables hold both those values. The function execute() run the PDO query statement.
PDOStatement:: fetch method extracts a row from the set of results. PDO:: FETCH_ASSOC parameter says PDO to recover array value indexed by username and email of the table column. The array is $row.
Row no 36 to 41 – If and if-else condition checks the new user has entered the username and the email value already exists from the table or not.
Row no 42 – else if condition, the isset () function checks that no error has been found in the variable $errorMsg.
The first password text box value holding the variable $password. And the second PASSWORD_DEFAULT parameter used to define the hash password algorithm.
The hashed/encrypt password will be generated and this password store will be created in the variable $new_password.
Under in execute() function the function array () binds the values :uname, :uemail and :upassword in the insert query. All parameter values carry variables along with $username,$email and $new_password variables.
7. welcome.php
This page displays the logging in the user’s welcome message with username as well as a hyperlink to logout the user and diverts the login or index.php page.
$id = $_SESSION['user_login']; $select_stmt = $db->prepare("SELECT * FROM tbl_user WHERE user_id=:uid"); $select_stmt->execute(array(":uid"=>$id)); $row=$select_stmt->fetch(PDO::FETCH_ASSOC); if(isset($_SESSION['user_login'])) < ?>Welcome, ?>
Logout
7.1 Welcome Page Codes Logic Explanation :
Friends, I skip the simple logic of how to include the database connection file and how to start the session using session_start() because I have already discussed the login and registration codes above.
Row no 9 to 12 – If condition, To find a user_login session object, we use the $_SESSION[ ] superglobal array method. If not found then header () function sends to the index page. The unauthorized user does not have access to the welcome page without the session.
Row no 16 to 19 – Apply PDO select query inside the prepare() statement and select the user Id for that login.
The execute() function executes the query as well as within this function the array() function bind the :uid value place in select query. And this value carries by $id variable.
PDOStatement:: fetch method select a row from the set of results. PDO:: FETCH_ASSOC parameter orders PDO to retrieve array value indexed by the Id of the table column. The array is $row.
8. logout.php
In this file, we kill the session from the welcome page, along with clicking on the logout hyperlink, and send it all to the index.php / login page.
MySQL пароль () функция для PHP
Я пытался исследовать это, но у меня пока нет ответа. Программа, которую мой друг разработал, записывает в пароли MySQL db с помощью функции MySQL password(). Я ищу способ использовать это через веб-интерфейс, который я разработал, но до сих пор не повезло. У кого-нибудь есть предложения? Пароли выглядят так же, как в этом примере
mysql> SET old_passwords = 0; mysql> SELECT PASSWORD('mypass'); +-------------------------------------------+ | PASSWORD('mypass') | +-------------------------------------------+ | *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 | +-------------------------------------------+
Мне просто нужно выяснить, как превратить это в функцию i.e function password_hash Здесь остальные запросы для входа в систему
if (isset($_POST["username"], $_POST["password"], $_POST[$CONF["LOGIN_SIGNAL_TRIGGER"]])) < /* If we got a login signal, a password and a username, we will proceed to check login information. We will first extract the user row from the db. */ $user = myF(myQ(" SELECT `username`,`password`,`id`,`disable_until`,`active` FROM `[x]users` WHERE LCASE(`username`)='".strtolower($_POST["username"])."' ")); if (!$user["id"]) $GLOBALS["LOGIN_FAIL_TYPE"] = "e.user"; elseif ($user["active"] != 1 && $CONF["LOGIN_REQUIRE_ACTIVE"]) $GLOBALS["LOGIN_FAIL_TYPE"] = "e.active"; else < /* If the user account 'disabled' value is greater than the actual date value, and that the bruteforce protection system is enabled, we will show an error message */ if (($user["disable_until"] >date("U")) && ($CONF["LOGIN_BRUTEFORCE_PROTECT:ENABLE"])) < $GLOBALS["LOGIN_FAIL_TYPE"] = "e.bruteforce"; (isset($_SESSION["loginFailCount"])?session_unregister('loginFailCount'):false); >/* Account is not disabled */ else < if ((isset($_SESSION["loginFailCount"])) && ($_SESSION["loginFailCount"] >$CONF["LOGIN_BRUTEFORCE_FAILCOUNT"])) < myQ("UPDATE `[x]users` SET `disable_until` = ".(date("U")+$CONF["LOGIN_BRUTEFORCE_DISABLE_DURATION"])." WHERE LCASE(`username`)='".strtolower($_POST["username"])."' LIMIT 1" ); (isset($_SESSION["loginFailCount"])?session_unregister('loginFailCount'):false); $GLOBALS["LOGIN_FAIL_TYPE"] = "e.bruteforce"; >else < /* All the information correct, we will proceed to login */ if ($user["password"] == md5(trim($_POST["password"]))) < $_SESSION["id"] = (integer)$user["id"]; session_write_close(); /* Update the last login key */ $me_last_login = me("last_login"); myQ("UPDATE `[x]users` SET `last_login`='".date("U")."' WHERE `id`='".me('id')."'"); /* Route the user */ if (!$GLOBALS["WAP_MODE"]) < header("Location: ".(!$me_last_login?$CONF["LOGIN_FIRST_ROUTE_TO"]:$CONF["LOGIN_ROUTE_TO"])); >else header("Location: "); > else < (isset($_SESSION["loginFailCount"])?$_SESSION["loginFailCount"]++:$_SESSION["loginFailCount"]=1); $GLOBALS["LOGIN_FAIL_TYPE"] = "e.password"; >> > > > if ((isset($_GET[$CONF["LOGOUT_SIGNAL_TRIGGER"]])) && (!isset($_POST[$CONF["LOGIN_SIGNAL_TRIGGER"]]))) < /* Handle admin swapping */ if (isset($_SESSION["swap_id"])) < $_SESSION["id"] = $_SESSION["swap_id"]; session_unregister("swap_id"); header("Location: ?L=admin.index"); >else < (isset($_SESSION["id"])?session_unregister('id'):false); (isset($_SESSION["SELF_USER_DATA"])?session_unregister('SELF_USER_DATA'):false); header("Location: "); > >