PHP Tutorial 05 : Session and Cookies

Session.

In the web server cannot recognize you because HTTP address does not maintain your state. But this php session variable help to store your data by avoiding above problem. This session can hold the one user information to all pages in the application.

  • PHP Session is best way to store the information in variable.

  • Session starting function is session_start().
  • Session php global variable $_SESSION.
  • If you want, you can modify the session variables.
  • Session can destroy using session_unset() and session_destroy().
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session
session_destroy();
?>

</body>
</html>

Cookies.

Cookie file is very small like 4KB and less. After setting the cookies all pages to request to display the cookies name and value. But cookies can be read from domain only.

  • A cookie created by a user can only be visible to them. Other users cannot see its value.
  • Web browsers have option to disable the cookies. Php can pass the cookies token to the URL.

How to work cookies??

  • First step – User request from the page that store the cookies.
  • Second step – Server set the cookies on the user’s computer.
  • Third step – When other page request from the user the cookies name and value will display.
  • Track the state of the application – Cookies paths depend on the browser and usually internet explorer stores them.
  • Personalizing the user experience – Allowing users to select their preferences
  • Tracking the visiting users.
  • How to store cookies more about this.
<?php

setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]);

?>

Setcookie is a php function that we can use to create the cookies.

cookie_name this is mandatory and set the cookies name.

cookie_value this is also mandatory and use to store the cookies value.

[expiry_time], [cookie_path] this both are optional and use to set the expiry time of the cookies and set the cookies path.

[domain], [secure] this is also optional and use to define the cookies access hirachy.

[httponly] – optional and if we set this as true JavaScript cannot access this only can access other client-side scripting language.

PHP Tutorial 3.

One thought on “PHP Tutorial 05 : Session and Cookies”

Leave a Reply

Your email address will not be published. Required fields are marked *