Browsing articles in "Blog"

Part 6: Create your own Login System using PHP and MySql

Nov 28, 2022   //   by h05t5cr1pt3r   //   Blog  //  No Comments

6. Creating the Profile Page

The profile page will display the account information for the logged-in user.

Edit the profile.php file and add the following code:

<?php
// We need to use sessions, so you should always start sessions using the below code.
session_start();
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
	header('Location: index.html');
	exit;
}
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phplogin';
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
	exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// We don't have the password or email info stored in sessions so instead we can get the results from the database.
$stmt = $con->prepare('SELECT password, email FROM accounts WHERE id = ?');
// In this case we can use the account ID to get the account info.
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($password, $email);
$stmt->fetch();
$stmt->close();
?>

The above code retrieves additional account information from the database, as before with the home page, we didn’t need to connect to the database because we retrieved the data stored in sessions.

We’re going to populate all the account information for the user and therefore we must retrieve the password and email columns from the database. We don’t need to retrieve the username or id columns because we’ve them stored in session variables that were declared in the authenticate.php file.

After the closing tag, add the following code:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Profile Page</title>
		<link href="style.css" rel="stylesheet" type="text/css">
		<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
	</head>
	<body class="loggedin">
		<nav class="navtop">
			<div>
				<h1>Website Title</h1>
				<a href="profile.php"><i class="fas fa-user-circle"></i>Profile</a>
				<a href="logout.php"><i class="fas fa-sign-out-alt"></i>Logout</a>
			</div>
		</nav>
		<div class="content">
			<h2>Profile Page</h2>
			<div>
				<p>Your account details are below:</p>
				<table>
					<tr>
						<td>Username:</td>
						<td><?=$_SESSION['name']?></td>
					</tr>
					<tr>
						<td>Password:</td>
						<td><?=$password?></td>
					</tr>
					<tr>
						<td>Email:</td>
						<td><?=$email?></td>
					</tr>
				</table>
			</div>
		</div>
	</body>
</html>

A simple layout that will populate account information. If you navigate to the profile.php file, it will look like the following:

http://localhost/phplogin/profile.php

PHP Loggedin Profile Page

Remember, the passwords are encrypted, so you cannot see the decrypted password unless you create a new session variable and store the password in the authenticate.php file.

Part 5: Create your own Login System using PHP and MySql

Nov 28, 2022   //   by h05t5cr1pt3r   //   Blog  //  No Comments

5. Creating the Home Page

The home page will be the first page our users see when they’ve logged-in. The only way they can access this page is if they’re logged-in, whereas if they aren’t, they will be redirected back to the login page.

Edit the home.php file and add the following code:

<?php
// We need to use sessions, so you should always start sessions using the below code.
session_start();
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
	header('Location: index.html');
	exit;
}
?>

Basically, the above code will check if the user is logged in, if they are not, they will be redirected to the login page. Remember the $_SESSION[‘loggedin’] variable we defined in the authenticate.php file? This is what we can use to determine whether users are logged in or not.

Now we can add some HTML to our home page. Below the closing tag, add the following code:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Home Page</title>
		<link href="style.css" rel="stylesheet" type="text/css">
		<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
	</head>
	<body class="loggedin">
		<nav class="navtop">
			<div>
				<h1>Website Title</h1>
				<a href="profile.php"><i class="fas fa-user-circle"></i>Profile</a>
				<a href="logout.php"><i class="fas fa-sign-out-alt"></i>Logout</a>
			</div>
		</nav>
		<div class="content">
			<h2>Home Page</h2>
			<p>Welcome back, <?=$_SESSION['name']?>!</p>
		</div>
	</body>
</html>

The above code is the template for our home page. On this page, the user will encounter a welcome message along with their name being displayed.

We need to add CSS for the home page. Add the following code to style.css file:

.navtop {
	background-color: #2f3947;
	height: 60px;
	width: 100%;
	border: 0;
}
.navtop div {
	display: flex;
	margin: 0 auto;
	width: 1000px;
	height: 100%;
}
.navtop div h1, .navtop div a {
	display: inline-flex;
	align-items: center;
}
.navtop div h1 {
	flex: 1;
	font-size: 24px;
	padding: 0;
	margin: 0;
	color: #eaebed;
	font-weight: normal;
}
.navtop div a {
	padding: 0 20px;
	text-decoration: none;
	color: #c1c4c8;
	font-weight: bold;
}
.navtop div a i {
	padding: 2px 8px 0 0;
}
.navtop div a:hover {
	color: #eaebed;
}
body.loggedin {
	background-color: #f3f4f7;
}
.content {
	width: 1000px;
	margin: 0 auto;
}
.content h2 {
	margin: 0;
	padding: 25px 0;
	font-size: 22px;
	border-bottom: 1px solid #e0e0e3;
	color: #4a536e;
}
.content > p, .content > div {
	box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.1);
	margin: 25px 0;
	padding: 25px;
	background-color: #fff;
}
.content > p table td, .content > div table td {
	padding: 5px;
}
.content > p table td:first-child, .content > div table td:first-child {
	font-weight: bold;
	color: #4a536e;
	padding-right: 15px;
}
.content > div p {
	padding: 5px;
	margin: 0 0 10px 0;
}

Now that we have our home page set-up, we can redirect our users from the authenticate.php file to our home page, edit authenticate.php and replace the following line of code:

echo 'Welcome ' . $_SESSION['name'] . '!';

With:

header('Location: home.php');

If you log in with the test account, you should see something like this:

http://localhost/phplogin/home.php

PHP Loggedin Home Page

This is a pretty basic home page. You can customize it to how you want now that you understand how it works.

Part 4: Create your own Login System using PHP and MySql

Nov 28, 2022   //   by h05t5cr1pt3r   //   Blog  //  No Comments

4. Authenticating Users with PHP

Now that we have our database setup, we can go ahead and start coding with PHP. We’re going to start with the authentication file, which will process and validate the form data that we’ll send from our index.html file.

Edit the authenticate.php file and add the following:

<?php
session_start();
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phplogin';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
	// If there is an error with the connection, stop the script and display the error.
	exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}

Initially, the code will start the session as this enables us to preserve account details on the server and will be used later on to remember logged-in users.

Connecting to the database is essential. Without it, how can we retrieve and store information related to our users? Therefore, we must make sure to update the variables to reflect our MySQL database credentials.

Add below:

// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
	// Could not get the data that should have been sent.
	exit('Please fill both the username and password fields!');
}

The above code will make sure the form data exists, whereas if the user tries to access the file without submitting the form, it will output a simple error.

Add below:

// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
	// Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
	$stmt->bind_param('s', $_POST['username']);
	$stmt->execute();
	// Store the result so we can check if the account exists in the database.
	$stmt->store_result();


	$stmt->close();
}
?>

The above code will prepare the SQL statement that will select the id and password columns from the accounts table. In addition, it will bind the username to the SQL statement, execute, and then store the result.

After the following line:

$stmt->store_result();

Add:

if ($stmt->num_rows > 0) {
	$stmt->bind_result($id, $password);
	$stmt->fetch();
	// Account exists, now we verify the password.
	// Note: remember to use password_hash in your registration file to store the hashed passwords.
	if (password_verify($_POST['password'], $password)) {
		// Verification success! User has logged-in!
		// Create sessions, so we know the user is logged in, they basically act like cookies but remember the data on the server.
		session_regenerate_id();
		$_SESSION['loggedin'] = TRUE;
		$_SESSION['name'] = $_POST['username'];
		$_SESSION['id'] = $id;
		echo 'Welcome ' . $_SESSION['name'] . '!';
	} else {
		// Incorrect password
		echo 'Incorrect username and/or password!';
	}
} else {
	// Incorrect username
	echo 'Incorrect username and/or password!';
}

First, we need to check if the query has returned any results. If the username doesn’t exist in the database then there would be no results.

If the username exists, we can bind the results to both the $id and $password variables.

Subsequently, we proceed to verify the password with the password_verify function. Only passwords that were created with the password_hash function will work.

If you don’t want to use any password encryption method, you can simply replace the following code:

if (password_verify($_POST['password'], $password)) {

With:

if ($_POST['password'] === $password) {

However, I don’t recommend removing the hashing functions because if somehow your database becomes exposed, all the passwords stored in the accounts table will also be exposed. In addition, the user will have a sense of privacy knowing their password is encrypted.

Upon successful authentication from the user, session variables will be initialized and preserved until they’re destroyed by either logging out or the session expiring. These session variables are stored on the server and are associated with a session ID stored in the user’s browser. We’ll use these variables to determine whether the user is logged in or not and to associate the session variables with our retrieved MySQL database results.

Did you know?The session_regenerate_id() function will help prevent session hijacking as it regenerates the user’s session ID that is stored on the server and as a cookie in the browser.

The user cannot change the session variables in their browser and therefore you don’t need to be concerned about such matter. The only variable they can change is the encrypted session ID, which is used to associate the user with the server sessions.

Now we can test the login system and make sure the authentication works correctly. Navigate to http://localhost/phplogin/index.html in your browser.

Type in a random username and password, and click the login button. It should output an error that should look like the following:

http://localhost/phplogin/authenticate.php

Authentication Incorrect Username PHP

Don’t worry, it’s not broken! If we navigate back to our login form and enter test for both the username and password fields, the authentication page will look like the following:

http://localhost/phplogin/authenticate.php

Authentication Loggedin PHP

If you receive an error, make sure to double-check your code to make sure you haven’t missed anything or check if the test account exists in your database.

Part 3: Create your own Login System using PHP and MySql

Nov 28, 2022   //   by h05t5cr1pt3r   //   Blog  //  No Comments

3. Creating the Database and setting-up Tables

For this part, you will need to access your MySQL database, either using phpMyAdmin or your preferred MySQL database management application.

Follow the below instructions if you’re using phpMyAdmin.

  • Navigate to: http://localhost/phpmyadmin/
  • Click the Databases tab at the top
  • Under Create database, enter phplogin in the text box
  • Select utf8_general_ci as the collation
  • Click Create

You can use your own database name, but for this tutorial, we’ll use phplogin.

What we need now is an accounts table as this will store all the accounts (usernames, passwords, emails, etc) that are registered with the system.

Click the database on the left side panel (phplogin) and execute the following SQL statement:

CREATE TABLE IF NOT EXISTS `accounts` (
	`id` int(11) NOT NULL AUTO_INCREMENT,
  	`username` varchar(50) NOT NULL,
  	`password` varchar(255) NOT NULL,
  	`email` varchar(100) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `accounts` (`id`, `username`, `password`, `email`) VALUES (1, 'test', '$2y$10$SfhYIDtn.iOuCW7zfoFLuuZHX6lja4lF4XA4JqNmpiH/.P3zB8JCa', 'test@test.com');

On phpMyAdmin this should look like:

http://localhost/phpmyadmin/

phpMyAdmin Accounts Table

The above SQL statement code will create the accounts table with the columns idusernamepassword, and email.

The SQL statement will insert a test account with the username: test, and the password: test. The test account will be used for testing purposes to ensure our login system is functioning correctly.

Pages:«1234567...18»