• PHP Video Tutorials

PHP - session_encode() Function



Definition and Usage

Sessions or session handling is a way to make the data available across various pages of a web application. The session_encode() function encodes the data in the session into an encoded string and returns it.

Syntax

session_encode();

Parameters

This function does not accept any parameters.

Return Values

This function encodes the data in the current session and returns it in the form of encoded serialized string.

PHP Version

This function was first introduced in PHP Version 4 and works in all the later versions.

Example 1

Following example demonstrates the usage of the session_encode() function.

<html>   
   <head>
      <title>Setting up a PHP session</title>
   </head>   
   <body>
      <?php 
         //Starting the session
         session_start();   
         $_SESSION['data'] = "This is sample data";
         $res = session_encode();
         echo "Encoded Data: ". $res;
      ?>
   </body>   
</html>

One executing the above html file it will display the following message −

Encoded Data: data|s:19:"This is sample data";

Example 2

Following is another example of this function, in here we have two pages from the same application in the same session −

session_page1.htm

<html>
   <body>
      <form action="#" method="post">
         <br>
         <label for="fname">Enter the values click Submit and click on Next</label>
         <br><br><label for="fname">Name:</label>
         <input type="text" id="name" name="name"><br><br>
         <label for="lname">Age:</label>
         <input type="text" id="age" name="age"><br><br>           
         <input type="submit" name="SubmitButton"/>
         <?php 
            echo '<br><br /><a href="session_page2.htm">Next</a>';
               if(isset($_POST['SubmitButton'])){ 
               //Starting the session	
               session_start();
               $_SESSION['name'] = $_POST['name'];
               $_SESSION['age']  = $_POST['age'];
               $res = session_encode();
               echo "<br><br>Encoded Data: ". $res;
            }
         ?>
      </form>
   </body>
</html>

This will produce the following output −

Session start

After clicking on the Submit button the above page looks like −

Session encode

On clicking on Next the following file is executed.

session_page2.htm

<html>   
   <head>
      <title>Second Page</title>
   </head>
   <body>
      <?php
         //Session started
         session_start();
         $_SESSION['City'] = 'Hyderabad'; 
         $_SESSION['Phone'] = '9848022338';
         $res = session_encode();
         echo "Encoded Data: ". $res;
      ?>   
   </body>   
</html>

This will produce the following output −

Encoded Data: data|s:19:"This is sample data";name|s:7:"Krishna";age|s:2:"30";City|s:9:"Hyderabad";Phone|s:10:"9848022338";
php_function_reference.htm
Advertisements