Verification: a143cc29221c9be0

Php change session cookie name

What is state management?

PHP allows us to save certain states of the application either on the server itself, or in the user’s browser. PHP provides us with two different techniques to manage states in a web application:

  1. Sessions: Server Side State Management
  2. Cookies: Client Side State Management

What is a session

Sessions are states that are saved to the server (like a unique ID), or if a user is logged into their account.

note Because sessions are not stored in the browser like cookies, it is a more secure option.

As an example, let’s consider a social media application like Facebook.

When users log into their Facebook account, the application remembers who they are until they log out. When logged in, a user has access to special features such as sending messages, uploading images and videos, joining groups etc.

The application tracks these states and stores them as a session on the server. As soon as the user is logged out, the session is destroyed.

How to start a session and store session data

To start a session in PHP, we use the session_start() function. We store session data by using the $_SESSION superglobal.

// start a session
session_start();

// set a session variable
$_SESSION["session_variable_name"] = session_variable_value;

The session_start() function must be the first statement in the document.

Example: main.php - start a session and store session data

php

// start a session
session_start();

// set a session variable
$_SESSION["username"] = "John";
$_SESSION["userID"] = 1;

?>


Sessions page



In the example above we also create an html hyperlink to another page, which will demonstrate how sessions save data across pages.

How to access session data

Before we access the session data set up in the previous section, create the sessions.php file in your main directory.

If you have been following along with the course and you’re working in Atom, follow the steps below.

  1. Inside Atom, navigate to your /PHPProjects/ folder.
  2. In the Project Pane, right-click on the /PHPProjects/ folder and select New File .
  3. Name the file “sessions.php” and press Enter .

We access session data in the same way we would access an array element.

Example: sessions.php - access session data

php
session_start();

echo "Hello " . $_SESSION["username"];

?>

When we run the main.php file, it stores the session data. Clicking the link takes us to a new page where we display the stored data. The username value survived across pages.

note We must remember to start a session with the session_start() function, even on pages that only access session data. The session start function will fetch an ongoing session if one has already been started elsewhere.

How to change session data

Session variables are mutable, which means they can be changed during runtime. To change the value of a session variable, we simply assign a new value to it.

 $_SESSION["session_variable_name"] = "new_value";

Example: main.php - change session data

php

// start a session
session_start();

// set a session variable
$_SESSION["username"] = "Jane";
$_SESSION["userID"] = 1;

?>


Sessions page



In the example above, we change the username session variable from John to Jane. If we run main.php and click on the link, the new name will be printed to the page.

How to remove stored session data from variables

If we want to clear out all the stored values from session variables, we use the session_unset() function.

Example: session.php - remove stored session data from variables

php
session_start();

echo "Hello " . $_SESSION["username"];

// unset username value
session_unset();

// try to print username to the page
echo $_SESSION["username"];

?>

After we unset the value of the username variable, we can no longer print it and the interpreter will raise an Undefined index error.

 Notice: Undefined index: username on line 10

How to destroy a session

We can destroy a whole session completely with the session_destroy() function.

Example: sessions.php - destroy a session

php
session_start();

echo "Hello " . $_SESSION["username"];

// unset username value
session_destroy();

// try to print username to the page
echo $_SESSION["username"];

?>

When the session is destroyed, both echo statements will not be able to print the username variable, and the interpreter will raise an error.

Notice: Undefined index: username on line 4
Hello
Notice: Undefined index: username on line 10

note It’s important to note that destroying a session may take some time, it is not always immediate.

Typically, a session is destroyed after logout or checkout etc. to clean the session variable of the user specific data.

What is a cookie

Cookies are states that are saved to the user’s system, instead of the server. Unlike a session, a cookie has a 1024 byte size limit. Cookies are sent to the web server as header information in every HTTP request.

note Cookies are not stored on the server, they can be modified and deleted. Cookies are less reliable and secure than sessions.

As an example, let’s consider an application with a member area. Once a user enters their log in details, a cookie is created on that user’s system that saves those details.

If the user comes back to the application, the login details can be automatically filled into the form so that the user doesn’t have to repeat the process.

Cookies are also commonly used to serve advertisements based on products that the user views around the web. For example, if a user views a product on Amazon, they will find advertisements of similar products when using Facebook or Google services.

How to set a cookie

PHP provides us with the setcookie() function to create, or set, a cookie.

 setcookie(name, value, expiration, path, domain, secure);

The first argument, name, is mandatory for every cookie. The rest of the arguments are optional, but recommended.

Argument Usage
name Required. The name the cookie will be referred to. Must be a string.
value Optional. The value of the cookie.
expiration Optional. If an expiration time is not set, the cookie will expire when the browser is closed.
path Optional. The path on the server the cookie will be available on. The cookie can be set to '/' to be available to the entire domain.
domain Optional. The (sub)domain that the cookie is available to. Sub-domains of the specified domain are automatically included.
secure Optional. If set to true, the cookie will only be set for a HTTPS secure connection.

Example: how to set a cookie

php

// Expires when the browser closes
setcookie("UserID", 007);

// Expires in 1 minute (60 seconds)
setcookie("SelfDestructMsg", "1 minute", time()+60)

// Only available to a specific subdomain over HTTPS
setcookie("Name", "Bond, James", time()+60, "/totally_not_cookies/", "agents.mi6.com", 1);

?>

The value portion of the cookie will automatically be urlencoded when the cookie is sent. Characters such as a space and . will be converted to underscores. When the cookie is received, it will be automatically decoded and assigned to a variable with the same name.

The expiration time is often confusing for many beginners that aren’t used to working with the UNIX timestamp. In such a case we can use the strtotime() function which converts time from a string into the correct time.

Example: alternate expiration time

php

// Expires in 30 days
setcookie("UserID", 007, strtotime('+30 days'));

?>

How to access cookie data

We access a cookie’s value via the $_COOKIE superglobal by specifying its name as the key.

php

setcookie("Name", "Bond, James", time()+60);

echo "Agent: " . $_COOKIE["Name"];

?>

How to change cookie data

We can change any argument of the cookie, except the name, by assigning a new value. When a new name is assigned, it will create a new cookie instead of changing the current cookie.

Example: how to change cookie data

php

setcookie("Name", "Hunt, Ethan", time()+5);

echo "Agent: " . $_COOKIE["Name"];

?>

How to delete a cookie

We delete a cookie by setting its expiration time to anything in the past.

Example: how to delete a cookie

php

// Current time - 60 minutes
setcookie("Name", "Hunt, Ethan", time()-3600);

echo "Agent: " . $_COOKIE["Name"];

?>

When a cookie is deleted and we try to access it, the interpreter will raise an Undefined index error.

Output: deleted cookie error

 Notice: Undefined index: Name on line 6

The error is raised as an undefined index because the index Name in the $_COOKIE superglobal doesn’t exist anymore.

There is a risk of the user modifying their system’s time backwards so that the cookie does not expire. We recommend that the cookie be set to expire one second into the future, instead of in the past.

Example: delete a cookie in a second

php

// Current time - 60 minutes
setcookie("Name", "Hunt, Ethan", time()+1);

echo "Agent: " . $_COOKIE["Name"];

?>

How to test if cookies can be set

With all the privacy concerns these days, many users disable cookies in their browsers. If we want to know if a cookie can be set in a user’s browser, we have to try and create a cookie. If the attempt is successful, we know that cookies can be set.

Example: test if a cookie can be set

php

setcookie("isAllowed", 1);

if(isset($_COOKIE["isAllowed"])) {
    echo "Cookies are allowed";
} else {
    echo "Cookies are not allowed";
}

?>

What is Cookie?

A cookie is a small file with the maximum size of 4KB that the web server stores on the client computer.

Once a cookie has been set, all page requests that follow return the cookie name and value.

A cookie can only be read from the domain that it has been issued from. For example, a cookie set using the domain www.guru99.com can not be read from the domain career.guru99.com.

Most of the websites on the internet display elements from other domains such as advertising. The domains serving these elements can also set their own cookies. These are known as third party cookies.

A cookie created by a user can only be visible to them. Other users cannot see its value.

Most web browsers have options for disabling cookies, third party cookies or both.

If this is the case then PHP responds by passing the cookie token in the URL.

The diagram shown below illustrates how cookies work.

Here,

1) A user requests for a page that stores cookies

2) The server sets the cookie on the user’s computer

3) Other page requests from the user will return the cookie name and value

In this tutorial, you will learn-

  • Why and when to use Cookies?
  • Creating Cookies
  • Retrieving the Cookie value
  • Delete Cookies
  • What is a Session?
  • Why and when to use Sessions?
  • Creating a Session
  • Destroying Session Variables

Why and when to use Cookies?

  • Http is a stateless protocol; cookies allow us to track the state of the application using small files stored on the user’s computer.

    The path were the cookies are stored depends on the browser.

    Internet Explorer usually stores them in Temporal Internet Files folder.

  • Personalizing the user experience – this is achieved by allowing users to select their preferences.

    The page requested that follow are personalized based on the set preferences in the cookies.

  • Tracking the pages visited by a user

Creating Cookies

Let’s now look at the basic syntax used to create a cookie.

HERE,

  • Php“setcookie” is the PHP function used to create the cookie.
  • “cookie_name” is the name of the cookie that the server will use when retrieving its value from the $_COOKIE array variable. It’s mandatory.
  • “cookie_value” is the value of the cookie and its mandatory
  • “[expiry_time]” is optional; it can be used to set the expiry time for the cookie such as 1 hour. The time is set using the PHP time() functions plus or minus a number of seconds greater than 0 i.e. time() + 3600 for 1 hour.
  • “[cookie_path]” is optional; it can be used to set the cookie path on the server. The forward slash “/” means that the cookie will be made available on the entire domain. Sub directories limit the cookie access to the subdomain.
  • “[domain]” is optional, it can be used to define the cookie access hierarchy i.e. www.cookiedomain.com means entire domain while www.sub.cookiedomain.com limits the cookie access to www.sub.cookiedomain.com and its sub domains. Note it’s possible to have a subdomain of a subdomain as long as the total characters do not exceed 253 characters.
  • “[secure]” is optional, the default is false. It is used to determine whether the cookie is sent via https if it is set to true or http if it is set to false.
  •  “[Httponly]” is optional. If it is set to true, then only client side scripting languages i.e. JavaScript cannot access them.

Note: the php set cookie function must be executed before the HTML opening tag.

Let’s now look at an example that uses cookies.

We will create a basic program that allows us to store the user name in a cookie that expires after  ten seconds.

The code below shows the implementation of the above example “cookies.php”.

Output:

the cookie has been set for 60 seconds

Retrieving the Cookie value

Create another file named “cookies_read.php” with the following code.

Output:

Array ( [PHPSESSID] => h5onbf7pctbr0t68adugdp2611 [user_name] => Guru99 )

  Note: $_COOKIE is a PHP built in super global variable.

It contains the names and values of all the set cookies.

The number of values that the

$_COOKIE array can contain depends on the memory size set in php.ini.

The default value is 1GB.

Testing our application.

Let’s assume you have saved your PHP files in phptus folder.

  • Step 1 – open your web browser and enter the URL http://localhost/phptuts/cookies_read.php

Note: Only an empty array has been displayed

  • Step 2 – Browser to the URL http://localhost/phptuts/cookies.php

  • Step 3 – Switch back to the first tab then click on refresh button

Wait for a minute then click on refresh button again. What results did you get?

Delete Cookies

  • If you want to destroy a cookie before its expiry time, then you set the expiry time to a time that has already passed.
  • Create a new filed named cookie_destroy.php with the following code
  • Repeat steps 1 through to 3 from the above section on retrieving cookie values.
  • Open the URL http://localhost/phptuts/cookie_destroy.php
  • Switch to the URL http://localhost/phptuts/cookies_read.php what results does it display?

What is a Session?

  • A session is a global variable stored on the server.
  • Each session is assigned a unique id which is used to retrieve stored values.
  • Whenever a session is created, a cookie containing the unique session id is stored on the user’s computer and returned with every request to the server.  If the client browser does not support cookies, the unique php session id is displayed in the URL
  • Sessions have the capacity to store relatively large data compared to cookies.
  • The session values are automatically deleted when the browser is closed. If you want to store the values permanently, then you should store them in the database.
  • Just like the $_COOKIE array variable, session variables are stored in the $_SESSION array variable. Just like cookies, the session must be started before any HTML tags.

Why and when to use Sessions?

  • You want to store important information such as the user id more securely on the server where malicious users cannot temper with them.
  • You want to pass values from one page to another.
  • You want the alternative to cookies on browsers that do not support cookies.
  • You want to store global variables in an efficient and more secure way compared to passing them in the URL
  • You are developing an application such as a shopping cart that has to temporary store information with a capacity larger than 4KB.

Creating a Session

In order to  create a session, you must first call the PHP session_start function and then store your values in the $_SESSION array variable.

 Let’s suppose we want to know the number of times that a page has been loaded, we can use a session to do that.

The code below shows how to create and retrieve values from sessions

Output:

You are visitor number 1

Destroying Session Variables

The session_destroy() function is used to destroy the whole Php session variables.

If you want to destroy only a session single item, you use the unset() function.

The code below illustrates how to use both methods.

  Session_destroy removes all the session data including cookies associated with the session.

Unset only frees the individual session variables.

Other data remains intact.