how to create a session in php

What is Session in php –:Cookies are stored on browser window means it stored on user side.  it is possible for a hacker to easily hack the cookie content to insert potentially harmful data in your application that might break your application.

Also every time the web  browser requests a url to the server.All the cookie data for a website is automatically sent to the server within the request. It means if you have stored 10 cookies on user’s system, each having 8 KB in size, the browser needs to upload 40 KB of data each time the user views a page.This will definitely affect your site’s performance.

The solution of this problem in php session. It stores  data on the server side . A session based environment every user is identified through a unique number called session identifier or (SID). This unique session ID is used to link each user with their own information on the server like emails, posts, etc.

Create a session in php-: Before you start to create a session it is necessary to know that a php engine automatically created a session in php.

session create

In the php you can use function for creating a session variable. we can use session_start() function for creating a session for example

 <?php

  session_start();  // for start a session in php

?>
<html>
 <body>
<?php
  // Set session variables
   $_SESSION["authorname"] = "Vikram";
   $_SESSION["favoritefield"] = "Software";
   echo "Session variables name are set";
?>
 </body>
</html>

Output of this program

Session variables are set

 

how to Get session in php-: After creating a session we get this session.For getting this session we use this syntax as like

  
<?php

   session_start(); // for start a session in php
 ?>
<html>
<body>

<?php
// Echo session variables that were set on previous page

 echo "author name is" . $_SESSION["authorname"] . ".<br>";
 echo "Favorite field is" . $_SESSION["favoritefield"] . ".";

?>
</body>
</html>


Output of this program

author name is vikram
favorite field is software

Modify a session in php -:  For editing in session or modify session we can create this function print_r($_SESSION)

 <?php
   
   $_SESSION["favoritefield"] = "software";
   print_r($_SESSION);

?>

modify a session

Delete a session in php: Delete a session in php we use session_destroy() function. For example

<?php

 session_start(); // for start a session in php

 ?>

<html>
  <body>
    <?php
  
      session_destroy();  //delete a session
      echo "all session are delete";
    ?>
  </body>
</html>

Output of this program

all session are delete 

 

Leave a Comment