PHP Program
PHP Program
// Form.php
<!DOCTYPE html>
<html>
<body>
<form method="post" action="login.php">
User Id: <input type="text" name="userid"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
// Login.PHP
<!DOCTYPE html>
<html>
<body>
<?php
$uid = $_POST['userid'];
$pw = $_POST['password'];
if($uid == 'ben' and $pw == 'ben23')
{
session_start();
$_SESSION['sid']=session_id();
echo "Logged in successfully";
}
?>
</body>
</html>
// Logout.PHP
<!DOCTYPE html>
<html>
<body>
<?php
echo "Logged out successfully";
session_start();
session_destroy();
?>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Session Example</title>
</head>
<body>
if($_SESSION['name']) {
header('location: printName.php');
}
}
?>
</body>
</html>
Explanation
In this example, we are taking a text input in the form of name and storing it in the
name session variable. Note, this is the how the session variables are
defined, $_SESSION['name']
Next, note that we have included session_start() at the beginning of each PHP file.
This will ensure that we can safely access the variable defined in other page, by just
using $_SESSION['name'].
printName.php
<?php session_start();
//Put session start at the beginning of the file
?>
<!DOCTYPE html>
<html>
<head>
<title>Print Name</title>
</head>
<body>
</body>
</html>
Explanation
In printName.php file, echoing the session name variable prints the name we have
inputted from user in another page.
<?php
//PHP program to create an object of a class and access class
attributes.
class Student
{
//Attributes
public $id;
public $name;
public $per;
}
$S = new Student();
$S->id = 101;
$S->name = "Rohit Kohli";
$S->per = 78.23;
Output
Student Id : 101
Student Name : Rohit Kohli
Student Percentage : 78.23