session example in php

Example 1: php sessions

<?php
  	// Start new or resume existing session.
  	session_start();
	
	// Add values to the session.
	$_SESSION['item_name'] = 'value'; // string
	$_SESSION['item_name'] = 0; // int
	$_SESSION['item_name'] = 0.0; // float

	// Get session values.
	$value = $_SESSION['item_name'];
?>

Example 2: destroy session php

<?php 
 session_start(); // start session
 session_destroy();  // Delete whole session
// OR
unset($_SESSION['username']); // delete any specific session only
?>

Example 3: create session in php

<?php 
  // Start the session
  session_start();

  // Set session variables
  $_SESSION["color"]= "blue";
  $_SESSION["animal"]= "dog";
  echo "The session variable are set up.";
?>

Example 4: session php

<?php
// start session before any HTML
session_start();

// create some variales in $_SESSION
$_SESSION['name'] = 'myname';
$_SESSION['surname'] = 'mysurname';
$_SESSION['age'] = 24;
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>My page</title>
    </head>
    <body>
    <p>
        Hey <?php echo $_SESSION['name']; ?> !<br />
        How are you today ?
    </p>

Example 5: $_SESSION php example

<?php
session_start();
echo session_id();
?>

Example 6: php session

/*Sessions are stored on the server
Sessions are a way to carry data across multiple pages. 
Typically if we set a variable on one page, it wouldn't be available 
on the next page. This is where Sessions come in. Unlike cookies session
data is not stored on the user's computer. It is stored on the server. 
In order to use session variables you have to start a session. 
Every page, that you want to use that data in, you have to use 
session_start.

If you want to unset one of these sessions you can use session_unset

youcan destry the session with session_destroy
*/

<?php if(isset($_POST['submit']))
{ session_start(); // that will start the session
$_SESSION['name'] = htmlentities($_POST['name']);
$_SESSION['email'] = htmlentities($_POST['email']);
header('Location: page2.php'); } ?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Sessions</title>
</head>
<body>
<form method="POST" action="<?php echo $server['PHP_SELF'];?>">
<input type="text" name="name" placeholder="Enter Name">
<br>
<input type="text" name="email" placeholder="Enter Email">
<br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>

Tags:

Php Example