Wednesday, January 7, 2015

Working with PHP Session (Create, Modify) etc.

Session helps in creating a file in a temporary directory on the server or inside the database as per its configuration and definition. This helps in authentication and validation of users and tokens, using session we can limit the access or broaden it. Before creating a session,PHP first creates a unique identifier for that particular session where a random string of 32 hexadecimal numbers, after that a cookie called PHPSESSID is created for that particular session in user’s computer to store unique session identification string. After that a file is created in server in a temporary directory or in database which contains the name of the unique identifier and details of users IP(Internet Protocol) and etc. according to logic used for creating session.

Syntax:
 Session_start();  


Example:

PHP Script (session.php)

 <?php  
 // Start the session  
 session_start();  
 ?>  
 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8"/>  
   <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <h3>Setting Session</h3>  
 <?php  
 // Set session variables  
 $_SESSION["session_var1"] = "PHP";  
 $_SESSION["session_var2"] = "Hello World";  
 echo "Session variables are set";  
 ?>  
 </body>  
 </html> 


Example of Get PHP Session Value:

PHP Script (session_get.php)

 <?php  
 // Start the session  
 session_start();  
 ?>  
 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8"/>  
   <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <h3>Get Session value</h3>  
 <?php  
 // Getting session variable value  
 echo "Variable1= ".$_SESSION["session_var1"];  
 echo "<br/>";  
 echo "Variable2= ".$_SESSION["session_var2"];  
 ?>  
 </body>  
 </html> 

Example of Modify PHP Session value:

Syntax:

 $_SESSION["session_variable"] = "New_value";  


Example:

PHP Script (session_modify.php)



 <?php  
 // Start the session  
 session_start();  
 ?>  
 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8"/>  
   <title>PHP</title>  
 </head>  
 <body>  
 <h3>Example of Modify Session</h3>  
 <?php  
 // Modify session  
 $_SESSION["session_var1"] = "CSS";  
 $_SESSION["session_var2"] = "This is modified";  
 echo "Session value is modified.";  
 ?>  
 </body>  
 </html> 

No comments:

Post a Comment