PHP interview questions and answers

Home >> PHP interview questions and answers  >>

  PHP interview questions and answers part - 4

This article will give you an overview of PHP cookie and session questions and answers that may be helpful for you in an interview or online test.

Cookie questions and answers

Question: What does $_COOKIE means?

$_COOKIE is an associative array of variables sent to the current PHP script using the HTTP Cookies.

Question: How to set cookies in PHP?

Syntex: setcookie(name,value,expire,path,domain,secure,httponly);

name: (Required) Name of the cookie.

value: (Required) Value of the cookie.

expire: (Optional) When the cookie expires. 

path: (Optional) Specifies the server path of the cookie. If set to "/", the cookie will be available within the entire domain. If set to "/php/", the cookie will only be available within the php directory and all sub-directories of php.

domain: (Optional) Specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to "example.com". Setting it to www.example.com will make the cookie only available in the www subdomain.

secure: (Optional) Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE.

httponly: (Optional) If set to TRUE the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible by scripting languages). This setting can help to reduce identity theft through XSS attacks. Default is FALSE.

Example:
$cookie_name = "php";
$cookie_value = "phpcodehub";

// cookie will expire in 1 hour
setcookie($cookie_name, $cookie_value, time() + 3600);

if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie named = " . $cookie_name . " is not set!";
} else {
    echo "Cookie " . $cookie_name . " is set!";
    // Retrieve a Cookie Value.
    echo "Value is : " . $_COOKIE[$cookie_name];
}

Note: If cookie expire time set to 0, or omitted, the cookie will expire at the end of the session (when your browser closes)

Example: 
// cookie will expire when the browser close
setcookie($cookie_name, $cookie_value);

Question: What is the meaning of a Persistent Cookie?
Where "expire" specifies when this cookie should be expired. If the expiration time is a future time, like 30 days from today, this cookie will be set as a persistent cookie.

The best way to set "expire" is use the time() function, which represents the current time in number of seconds. Example, 30 days from today can be expressed as "time()+60*60*24*30".

Question: What is the meaning of a Temporary Cookie?
If "expire" is not given, a temporary cookie will be created. Temporary Cookie is also called Session Cookie.

Session questions and answers

Question: what is the definition of a session?
A session is a logical object enabling us to preserve temporary data across multiple PHP pages.

Question: How to register Session in PHP?
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.

Example:
// Start the session
session_start();

// Set session variables
$_SESSION["name"] = "phpcodehub";
$_SESSION["php"] = "Hypertext Preprocessor";

// Retrieve session variables
echo $_SESSION["name"];
echo $_SESSION["php"];

Question: How to get current session id in PHP?
session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).

Example:
// get current session id
echo session_id();

Question: How to regenerate session id in PHP?
session_regenerate_id() will replace the current session id with a new one, and keep the current session information.

Example:
// regenerate session id
session_regenerate_id();

// get regenerated session id
echo session_id();

Question: When and why I should use session_regenerate_id()?
It mainly helps prevent session fixation attacks. 

Session Fixation is an attack that permits an attacker to hijack a valid user session. The attack explores a limitation in the way the web application manages the session ID, more specifically the vulnerable web application.

To prevent such attacks, assign the user a new session ID using session_regenerate_id() when he successfully signs in (or for every X requests). Now only he has the session ID, and your old (fixated) session ID is no longer valid.

Question: What is session default time in php
It depends on the server configuration or the relevant directives (session.gc_maxlifetime) in php.ini . Typically the default is 24 minutes (1440 seconds), but your webhost may have altered the default to something else. session.gc_maxlifetime() The value is set in Seconds.

Question: How to retrieve php server session timeout?

Example:
// retrieve php server session timeout
echo ini_get("session.gc_maxlifetime");

Question: How to change the session timeout in PHP?

Example:
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);

// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);

Question: How to get Cookie Name of the current session?
session_name() returns the name of the current session. If name is given, session_name() will update the session name and return the old session name.

Example:
// get Cookie Name of the current session
echo session_name(); 

Output will be:
PHPSESSID

Question: What is PHPSESSID?
PHP uses one of two methods to keep track of sessions. If cookies are enabled, then is saves session id in cookie name "PHPSESSID". If cookies are disabled, it uses the URL. Although this can be done securely.

Sessions can be stored in the querystring or a cookie depending on how you have PHP configured and also on whether or not your visitors allow cookies.

Question: How to change php session cookie name.
The variable you are looking for is session name. You can also alter this programmatically by calling session_name() before any call to session_start();

Example:
// Set custom session cookie name
session_name('CUSTOM_SESSION_COOKIE');

// Start the session
session_start();

Output will be:
// get Cookie Name of the current session
echo session_name(); 

CUSTOM_SESSION_COOKIE

Question: What is default session path?
Session Path: /temp folder on server
We can get this programmatically by calling ini_get("session.save_path");

 Example:
 // get session path
 echo ini_get("session.save_path");
 
 Output will be:
 c:/wamp/tmp : (It's not fixed, but it depends on where you have installed your server. I have my WAMP server in C drive so t's showing like this)

Question: How to change default session path?
We can also alter this programmatically by calling ini_set("session.save_path", 'c:/wamp/www/custom_temp'); before any call to session_start();

  Example:
  // Change default session path
 ini_set("session.save_path", 'c:/wamp/www/custom_temp');

 // Start the session
 session_start();

 Output will be:
 // get session path
 echo ini_get("session.save_path");
 c:/wamp/www/custom_temp : (It's not fixed, but it depends on where you have installed your server. I have my WAMP server in C drive so t's showing like this)

Question: How to delete session in php.
There are many ways to delete session.

1. The session_unset() function deletes only the variables from session - session still exists. Only data is truncated.

Example: session_unset(); 

2. Use unset() function destroy a specific session variable. 

Example: unset($_SESSION["php"]);

3. session_destroy() destroys all of the data associated with the current session. (deleting the whole session.)

Example: session_destroy();

Note : Before deleting session, we need to start session in php.

Example :
// Start the session
session_start();

// deletes only the variables from session
session_unset();

// destroy a specific session variable
unset($_SESSION["php"]);

// deleting the whole session.
session_destroy();

Question: How to save the session data into database?
To maintain the session data, we can use session_set_save_handler() function.
session_set_save_handler('open',  'close',  'read',  'write',  'destroy',  'gc');

In this function, we provide 6 callback functions which call automatically.
    
1. Opening the session data store.
2. Closing the session data store.
3. Reading session data.
4. Writing session data.
5. Destroying all session data.
6. Cleaning out old session data.

read more details about Storing PHP Sessions in a Database

Write your comment now