DEV Community

Ghulam Mujtaba
Ghulam Mujtaba

Posted on

Session and User Registration in PHP

Today, we will learn about PHP sessions and how to register a user using sessions. But first, let's understand what sessions are and how they work?

What is a Session?

A session is a way for a website to store information about a user's interactions with the site.

How Sessions Work

When a user visits a website, PHP creates a unique session identifier (SID) for that user. The SID is stored on the user's computer as a cookie. When the user navigates to a new page on the website, the SID is sent to the server along with the request. PHP uses the SID to retrieve the user's session data from the server.

  • Unique identifier for a user's session
  • Generated using session_start() function in PHP
  • Stored in the $_SESSION superglobal array
  • Used to store and retrieve data about the user's session
  • Usually a long string of characters

Starting a Session

To start a session, we use the session_start() function. This function must be called at the beginning of every script that uses sessions.
Let's Start to register a user,

Register a User

To register a user, we need to create a form that collects the user's email and password. We will use the $_POST superglobal array to access the form data. The registration form should include input fields for email and password, as well as a submit button.

Create a Registration Form

First, we need to add a route for registration in routes.php

$router->get('/register', 'controllers/registration/create.php');

Enter fullscreen mode Exit fullscreen mode

Then, we create a new file create.php in the controllers/registration directory that controls the view of user registration page

<?php

view('registration/create.view.php');
Enter fullscreen mode Exit fullscreen mode

And create a new file create.view.php in the views/registration directory, which will contain the code for the user registration page. To test if this file is working, add the following code to it:

<?php require base_path('views/partials/head.php') ?>
<?php require base_path('views/partials/nav.php') ?>

<main>
    <div class="flex min-h-full items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
<p>Register here!!!</p>
        </div>
</main>
<?php require base_path('views/partials/footer.php') ?>
Enter fullscreen mode Exit fullscreen mode

Register Form

As the project is working well , We then replace the code in the tag with the code from the Tailwind UI https://tailwindui.com/ and copy sign in page code from this. The registration form includes a heading, input fields for email and password, and a register button.

<?php require base_path('views/partials/head.php') ?>
<?php require base_path('views/partials/nav.php') ?>

<main>
    <div class="flex min-h-full items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
        <div class="w-full max-w-md space-y-8">
            <div>
                <img class="mx-auto h-12 w-auto" src="https://tailwindui.com/img/logos/mark.svg?color=indigo&shade=600"
                     alt="Your Company">
                <h2 class="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900">Register for a new
                    account</h2>
            </div>

            <form class="mt-8 space-y-6" action="/register" method="POST">
                <div class="-space-y-px rounded-md shadow-sm">
                    <div>
                        <label for="email" class="sr-only">Email address</label>
                        <input id="email" name="email" type="email" autocomplete="email" required
                               class="relative block w-full appearance-none rounded-none rounded-t-md border border-gray-300 px-3 py-2 text-gray-900 placeholder-gray-500 focus:z-10 focus:border-indigo-500 focus:outline-none focus:ring-indigo-500 sm:text-sm"
                               placeholder="Email address">
                    </div>

                    <div>
                        <label for="password" class="sr-only">Password</label>
                        <input id="password" name="password" type="password" autocomplete="current-password" required
                               class="relative block w-full appearance-none rounded-none rounded-b-md border border-gray-300 px-3 py-2 text-gray-900 placeholder-gray-500 focus:z-10 focus:border-indigo-500 focus:outline-none focus:ring-indigo-500 sm:text-sm"
                               placeholder="Password">
                    </div>
                </div>

                <div>
                    <button type="submit"
                            class="group relative flex w-full justify-center rounded-md border border-transparent bg-indigo-600 py-2 px-4 text-sm font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                    >
                        Register
                    </button>
                </div>

                <ul>
                    <?php if (isset($errors['email'])) : ?>
                        <li class="text-red-500 text-xs mt-2"><?= $errors['email'] ?></li>
                    <?php endif; ?>

                    <?php if (isset($errors['password'])) : ?>
                        <li class="text-red-500 text-xs mt-2"><?= $errors['password'] ?></li>
                    <?php endif; ?>
                </ul>
            </form>
        </div>
    </div>
</main>

<?php require base_path('views/partials/footer.php') ?>

Enter fullscreen mode Exit fullscreen mode

When a user enters the email and password in input fields and hits the register button it moves the user to next screen and shows 404error page to user as there is no file to navigate the user to next screen and to store the data which user provide at register page.

Store User Data

Firstly add a route for file that is used to store user registration data in database as

$router->post('/register', 'controllers/registration/store.php');

Enter fullscreen mode Exit fullscreen mode

Then Create a new file store.php in the controllers/registration directory. In which, We use the Database and Validator classes to validate the user's email and password, and store the user's data in the database. We also use the $_SESSION superglobal array to store the user's email in the session as:

<?php

use Core\App;
use Core\Database;
use Core\Validator;

$db = App::resolve(Database::class);

$email = $_POST['email'];
$password = $_POST['password'];

$errors = [];
if (!Validator::email($email)) {
   $errors['email'] = 'Invalid email address.';
}

if (!Validator::string($password, 7, 255)) {
    $errors['password'] = ' password must contain seven characters.';
}

if (! empty($errors)) {
    return view('registration/create.view.php', [
        'errors' => $errors
    ]);
}

$user = $db->query('select * from users where email = :email', [
    'email' => $email
])->find();

if ($user) {
    header('location: /');
    exit();
} else {
    $db->query('INSERT INTO users(email, password) VALUES(:email, :password)', [
        'email' => $email,
        'password' => $password // stores password in simple form
    ]);

    $_SESSION['user'] = [
        'email' => $email
    ];

    header('location: /');
    exit();
}
Enter fullscreen mode Exit fullscreen mode

If the provided email and password are correct, and the user clicks the Register button, the user will be redirected to the home page, where their profile photo will be displayed. However, if a user with the same email is already registered, the user will be redirected back to the home page without creating a new account. The user's registration data will be stored in the 'users' table in the database and the project is working well.

I hope that you have clearly understood it.

Top comments (0)