Tutorialspoint.com

PHP — Login Example

Php login script is used to provide the authentication for our web pages. the Script executes after submitting the user login button.

Login Page

Login page should be as follows and works based on session. If the user close the session, it will erase the session data.

      body < padding-top: 40px; padding-bottom: 40px; background-color: #ADABAB; >.form-signin < max-width: 330px; padding: 15px; margin: 0 auto; color: #017572; >.form-signin .form-signin-heading, .form-signin .checkbox < margin-bottom: 10px; >.form-signin .checkbox < font-weight: normal; >.form-signin .form-control < position: relative; height: auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 10px; font-size: 16px; >.form-signin .form-control:focus < z-index: 2; >.form-signin input[type="email"] < margin-bottom: -1px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; border-color:#017572; >.form-signin input[type="password"] < margin-bottom: 10px; border-top-left-radius: 0; border-top-right-radius: 0; border-color:#017572; >h2 

Enter Username and Password

else < $msg = 'Wrong username or password'; >> ?>
Click here to clean Session.

Logout.php

It will erase the session data.

It will produce the following result −

Источник

Авторизация через сессию на PHP

Наша авторизация должна работать так: пользователь, который хочет авторизоваться на сайте, заходит на страницу login.php , вбивает правильные логин и пароль и далее ходит по страницам сайта уже будучи авторизованным.

Чтобы другие страницы сайта знали о том, что наш пользователь авторизован, мы должны хранить в сессии пометку об этом.

Пока наша авторизация не совсем рабочая, так как сессию мы еще не подключили и другие страницы сайта не могут понять, авторизован пользователь или нет.

Будем хранить пометку об авторизации в переменной сессии $_SESSION[‘auth’] — если там записано true , то пользователь авторизован, а если null — то не авторизован.

Давайте внесем соответствующую правку в наш код:

Теперь на любой странице сайта мы можем проверить, авторизован пользователь или нет, вот таким образом:

Можно закрыть текст какой-нибудь страницы целиком для неавторизованного пользователя:

Можно закрыть только часть страницы:

Пусть на нашем сайте, кроме страницы login.php , есть еще и страницы 1.php , 2.php и 3.php . Сделайте так, чтобы к этим страницам мог получить доступ только авторизованный пользователь.

Пусть на нашем сайте есть еще и страница index.php . Сделайте так, чтобы часть этой страницы была открыта для всех пользователей, а часть — только для авторизованных.

Модифицируйте ваш код так, чтобы при успешной авторизации в сессию записывался также логин пользователя.

Сделайте так, чтобы при заходе на любую страницу сайта, авторизованный пользователь видел свой логин, а не авторизованный — ссылку на страницу авторизации.

Источник

PHP Login Script with Session

In this tutorial, let us create a login script with a session in PHP. It has a simple example of implementing user authentication. This example uses a standard login form to get the user login details. And it preserves the login state with PHP sessions.

Login would be the first step of many applications. Sometimes, part of the privileged functionalities of the application will ask users to log in.

So, the login script is an integral part of an application. I will present to you the implementation of the login system with minimal code.

Authentication will help us to identify genuine users. By enabling authentication, we can protect our website from anonymous access.

What is inside?

Ways to create an authentication system

There are different ways of implementing an authentication system. The most popular way is to get the username and password via a login form and authenticate based on them.

PHP Login Script with Session

Recently, authentication using OTP is also becoming the norm. The OTP will be dynamic and allowed for one-time.

For OTP authentication, the application sends it either via SMS or email. In a previous article, we have seen an example code in PHP to log in by sending OTP via email.

About this example

This example has the user’s database with name, email, password and more details. It has an HTML form with inputs to get the user login credentials.

The PHP code will receive the posted data when the user submits their login details. It compares the entered data against the user database.

If a match is found, then it sets the user login session. This authentication code preserves the user id in a PHP session. The existence of this session will state the user authentication status.

After authentication, the PHP $_SESSION super global variable will contain the user id. The $_SESSION[“member_id”] is set to manage the logged-in session. It will remain until log out or quit the browser.

During logout, we unset all the session variables using the PHP unset() function.

File structure

The below screenshot shows the organized file structure of this user login example. The Member.php is the model class with authentication functionalities.

The DataSource.php file contains functions to get a connection and access the database.

In a view directory, I have created all the UI-related files for the login and the dashboard interface. It also contains a stylesheet used for this UI.

The index.php is the landing page that checks the user’s logged-in session. Then it redirects users either to log in or to the dashboard.

The login-action.php and logout.php files are the PHP endpoints. They handle actions as requested by the users via the interactive authentication Interface.

Login Script with Session Example File Structure

User login interface

Creating an HTML form to log in is the first step. It is to get the login details from users.

This example has two fields, username and password, for user login.

I have specified the validation function and the PHP endpoint with the form tag.

The HTML contains elements to display client-side validation error. Also, it has the code to show a server-side error response based on the login result.

       
?>

Enter Login Details

Login form validation

This script is for validating the login data on the client side. If the users submit the login with empty fields, this script will return a false boolean.

When it returns false, it displays a validation error message to the users. By returning boolean 0, the form validation script prevents the login from proceeding further.

function validate() < var $valid = true; document.getElementById("user_info").innerHTML = ""; document.getElementById("password_info").innerHTML = ""; var userName = document.getElementById("user_name").value; var password = document.getElementById("password").value; if (userName == "") < document.getElementById("user_info").innerHTML = "required"; $valid = false; >if (password == "") < document.getElementById("password_info").innerHTML = "required"; $valid = false; >return $valid; > 

PHP code to process login

The login-action.php file receives and handles the posted login data. It sends the username and password to the processLogin() function.

This method gets the login details and compares them with the user database.

It prepares a query and binds the login parameters with it to find the match from the database. The processLogin() function will return the result if the login match is found.

On successful login, the login-action.php sets the logged-in user session. Otherwise, it will return an error by saying “Invalid Credentials”.

loginMember(); if (! $isLoggedIn) < $_SESSION["errorMessage"] = "Invalid Credentials"; >header("Location: ./index.php"); exit(); > ?> 

Get logged-in user profile data to display a welcome message

This code is to display the dashboard after login. The PHP code embedded with this HTML is for getting the user session and the user data from the database.

It displays the welcome message by addressing the user with their display name.

The dashboard contains a logout link in addition to the welcome text.

getMemberById($_SESSION["userId"]); if (! empty($memberResult[0]["display_name"])) < $displayName = ucwords($memberResult[0]["display_name"]); >else < $displayName = $memberResult[0]["user_name"]; >> ?>     
Welcome , You have successfully logged in!
Click to Logout.

Member.php

This is the PHP class created in this example to handle the login process. The getMemberById method request DataSource to fetch the member results.

ds = new DataSource(); > function getMemberById($memberId) < $query = "SELECT * FROM registered_users WHERE $paramType = "i"; $paramArray = array( $memberId ); $memberResult = $this->ds->select($query, $paramType, $paramArray); return $memberResult; > function processLogin($username) < $query = "SELECT * FROM registered_users WHERE user_name = ?"; $paramType = "s"; $paramArray = array( $username ); $memberResult = $this->ds->select($query, $paramType, $paramArray); return $memberResult; > function loginMember() < $memberResult = $this->processLogin($_POST["user_name"]); $loginPassword = 0; if (! empty($memberResult)) < $password = $_POST["password"]; $hashedPassword = $memberResult[0]["password"]; if (password_verify($password, $hashedPassword)) < $loginPassword = 1; >if ($loginPassword == 1) < $_SESSION["userId"] = $memberResult[0]["id"]; return $memberResult; >> > > ?> 

Redirect users to log in or Dashboard based on Session

A landing page index.php contains code to check logged-in sessions and route users accordingly. The following code shows how to redirect users based on the session.

Handling logout in PHP

Clicking the logout link from the dashboard calls this PHP script. This script clears the current login session and redirects users to the login. The logout code is,

DataSource.php

This class establishes a connection object to access the database based on the request. It has the select function to prepare a fetch query to return the results. This class is available in the project download zip linked at the end of this tutorial.

Database script

This script contains the CREATE statement for the registered_users table. Also, it has the data dump to check the example with test login details.

CREATE TABLE `registered_users` ( `id` int(8) NOT NULL, `user_name` varchar(255) NOT NULL, `display_name` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `email` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci; INSERT INTO `registered_users` (`id`, `user_name`, `display_name`, `password`, `email`) VALUES (1, 'admin', 'Kate Winslet', '$2a$10$0FHEQ5/cplO3eEKillHvh.y009Wsf4WCKvQHsZntLamTUToIBe.fG', 'kate@wince.com'); ALTER TABLE `registered_users` ADD PRIMARY KEY (`id`); ALTER TABLE `registered_users` MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; 

Test login details

After setting this example code and database on your computer, use the following test data to check the example login system.

Username: kate_91 
Password: kate@03 

PHP login script with session output

This output screenshot shows the login form interface. It has the input fields to get the user login details.

User Login Form Screenshot

This is the screenshot of the welcome message. Once logged in, the user will see this response in the browser.

This view will show a welcome message by addressing the logged-in user. It also has a link to log out, as shown below.

Источник

Читайте также:  Java declare class type
Оцените статью