Q:

Write a php program to set session on successful login

belongs to collection: PHP Programming Exercises

0

PHP set session on login

Write a php program to set session on successful login

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Solution

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" />
</form>

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

<?php
// initiate session
session_start();
// check that form has been submitted and that name is not empty
if ($_POST && !empty($_POST['name'])) {
// set session variable
$_SESSION['name'] = $_POST['name'];
}
?>
<html>
<head>
<title>Set Session</title>
</head>
<body>
<?php
// 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>';
}
?>
</body>
</html>

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Programming Exercises

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a program in PHP to read from directory... >>
<< There are two deals of an item to buy. The quantit...