Pages

Friday, September 21, 2012

Preserving data using PHP Session

PHP sessions are important when you build more customized web applications. These sessions store information across several accesses within your website.

To enable sessions, add the following above your PHP code:

Sample:
<?php
session_start();
?>

PHP uses session variables in the form of $_SESSION[""] to preserve data. You can differentiate between these variables by setting the index of the session array to your
unique identifier.

Sessions are terminated by using session_destroy() before ending your PHP code. Session variables will automatically be released after the call of session_destroy().

PHP code will look like this:

Save the code below as session_form.php
=======================================

<?php
session_start();

if($_SESSION["ctr"] >=3)
{
   session_destroy();
   echo “<script> alert(‘Session Terminated’)</script>”;
}


echo "Hello";
echo "<form name='form1' method='post' action='form_act.php'>";
echo "
Please Enter a string:
<input name='title' type='text'>
";
$_SESSION["ctr"] = $_SESSION["ctr"] + 1;
echo"<input name='Submit' type='submit' value='Submit'>";
echo "</form>";
?>

Save it as form_act.php
=======================

<?php
session_start();
echo "Value Passed by POST : <b>";
echo $_POST["title"];
echo "</b><br>";

echo "Value Passed Thru Sessions: <b>";
echo $_SESSION["ctr"];
echo "</b><br>";

echo "<a href=' onclick='javascript.history(1)'>Go Back</a>";
?>


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.