PHP set session on login

Write a program to set session on successful login.


As we know HTTP is a stateless protocol, when a user requests one page, followed by another, HTTP does not provide a way for you to tell that both requests came from the same user. The idea of session control is to be able to track a user during a single session on a website.

First, we create a form with a text field called name and a submit button. Then, we Set the method to post and action to submit.php. The form looks like this-

<form name="form" method="post" action="submit.php">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
<input type="submit" name="Submit" value="Submit" />

Create an another page 'submit.php' and insert the following code -

// initiate session
// check that form has been submitted and that name is not empty
if ($_POST && !empty($_POST['name'])) {
// set session variable
$_SESSION['name'] = $_POST['name'];
<title>Set Session</title>
// check session variable is set
if (isset($_SESSION['name'])) {
// if set, greet by name
echo 'Hi, '.$_SESSION['name'];
echo 'Welcome to this page.';
else {
// if not set, send back to login
echo 'Please <a href="form.php">Login</a>';

In the above example, If $_SESSION['name'] has been set, a welcome message is displayed. Otherwise, the page tells the visitor that it doesn’t recognize the user, and provides a link to login from the first page.

Related Articles

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters
PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Lock a file
PHP - Insert image in database

Read more articles

General Knowledge

Learn Popular Language