Showing posts with label PHP SESSIONS. Show all posts
Showing posts with label PHP SESSIONS. Show all posts

Monday, 24 September 2018

PHP Session: Use Multiple Session Same Request | Duplicate Session | Use Value Of Another Session | Value From Another Session

PHP Session: Use Multiple Session Same Request | Duplicate Session | Use Value Of Another Session | Value From Another Session.



<?php
$path = ini_get('session.save_path');
session_start();
$id = session_id();
$_SESSION["name"] = isset($_GET["name"]) ? $_GET["name"] : "No Name";
$_SESSION["tokens"] = array();
echo "<pre>";
echo "Session Save Path: " . $path . ",Session_id=$id\r\n\r\n";
willThisWork();
echo "\r\nORIGINAL_SESSION\r\n";
print_r($_SESSION);

function willThisWork() {
    $existing = session_id();
    session_write_close();

    ob_start();
    session_id("MyCommonSessionInstance");
    session_start();
    if (!isset($_SESSION["tokens"])) {
        $_SESSION["tokens"] = array();
    }
    for ($i = 0; $i < 10000; $i++) {
        array_push($_SESSION["tokens"], md5(time().rand(9999,999999)));
    }
    $start = microtime(true);
    if (count($_SESSION["tokens"]) > 100000) {
        $_SESSION["tokens"] = array_slice($_SESSION["tokens"], 75000);
    }
    $in_array = count($_SESSION["tokens"]).",EXISTS=" . (in_array($_SESSION["tokens"][count($_SESSION["tokens"]) - 1], $_SESSION["tokens"]));
    session_write_close();
    ob_get_clean();
    echo("TIME_TAKE=" . ((microtime(true) - $start) / 1000))." ms\r\n";


    session_id($existing);
    session_start();
    echo "COUNT=$in_array\r\n";
}
echo "</pre>";

And output is below:

Session Save Path: C:\xampp\tmp,Session_id=crolfji99hva2o0dflkg4ddj93

TIME_TAKE=1.2001037597656E-5 ms
COUNT=65000,EXISTS=1

ORIGINAL_SESSION
Array
(
    [name] => No Name
    [tokens] => Array
        (
        )

)

Monday, 20 July 2015

PHP: Store value from Dropdown in SESSION Using Ajax with Lightbox

Storing the value from dropdown box in session using ajax programming with lightbox means user will have only focus to dropdown box. Lightbox will be overlayed on website, so the dropdown box can easily get selected by user. Here is the tutorial, source code and demo link

index.php
<?php
session_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var height=$(window).height();
var width=$(window).width();
$(".black-overlay").css("display","block");
$(".form-area").css("display","block");
$(".black-overlay").css("height",height);
$(".form-area").css("margin-top",height/2);
$(".form-area").css("margin-left",width/2.6);

$('#city').change(function(){
$(".black-overlay").css("display","none");
$(".form-area").css("display","none");
var area=$('#city option:selected').val();
$.ajax({
type: "POST",
url: "ajax.php",
data: "area="+area ,
success: function(html){
$('#area').val(html);
}
});
});
});
</script>
<style type="text/css">
.black-overlay
{
background:#000;
opacity: 0.6;
position:fixed;
top: 0;
left: 0;
width: 100%;
z-index: 110000;
display:none;
}
.form-area
{
width: 300px;
margin:0 auto;
position: fixed;
z-index: 10000000;
display:none;
}
#city
{
padding: 7px 13px;
width: 226px;
height: 43px;
border: 1px solid #fff;
line-height: 50px;
font-size: 21px;
color: #000;
}
.select-city-text
{
color: #fff;
text-transform: uppercase;
font-family: verdana;
font-size: 20px;
margin: 0 0 8px 0;
letter-spacing: 9px;
}
</style>

</head>

<body>
<div class="black-overlay">
</div>

<form method="post" action="" class="form-area">
<div class="select-city-text">Select City</div>
<select id="city">
<option>Bangalore</option><option>Mysore</option><option>Bagalkot</option><option>Bangalore</option><option>Basavakalyan</option><option>Belgaum</option><option>Bellary</option><option>Bhadravati</option><option>Bidar</option><option>Bijapur</option><option>Bommanahalli</option>
</select>
</form>
<input type="text" id="area" />
</body>
</html>
ajax.php
Data passed to ajax.php will be stored in a SESSION
<?php
session_start();
if(!empty($_POST['area']))
{
$_SESSION['area']=$_POST['area'];
echo $_SESSION['area'];
}

?>

Saturday, 27 June 2015

PHP : Session handler via mySQL

<?php
class MySQLSessionHandler {
private $_dblink;
private $_sessionName;
private $_sessionTable;
CONST SESS_EXPIRE = 3600;
public function __construct($host, $user, $pswd, $db, $sessionName, $sessionTable) {
$this->_dblink = new mysqli($host, $user, $pswd, $db);
$this->_sessionName = $sessionName;
$this->_sessionTable = $sessionTable;
session_set_save_handler(
array($this, "session_open"),
array($this, "session_close"),
array($this, "session_read"),
array($this, "session_write"),
array($this, "session_destroy"),
array($this, "session_gc")
);
session_start();
}
function session_open($session_path, $session_name) {
$this->sessionName = $session_name;
return true;
}
function session_close() {
return 1;
}
function session_write($SID, $value) {
$stmt = $this->_dblink->prepare("
INSERT INTO {$this->_sessionTable}
(sid, value) VALUES (?, ?) ON DUPLICATE KEY
UPDATE value = ?, expiration = NULL
");
$stmt->bind_param('sss', $SID, $value, $value);
$stmt->execute();
session_write_close();
}
function session_read($SID) {
$stmt = $this->_dblink->prepare("
SELECT value FROM {$this->_sessionTable}
WHERE sid = ? AND UNIX_TIMESTAMP(expiration) + " .
self::SESS_EXPIRE . " > UNIX_TIMESTAMP(NOW())
");
$stmt->bind_param('s', $SID);
if ($stmt->execute()) {
$stmt->bind_result($value);
$stmt->fetch();
if (!empty($value)) {
return $value;
}
}
}
public function session_destroy($SID) {
$stmt = $this->_dblink->prepare("
DELETE FROM {$this->_sessionTable} WHERE SID = ?
");
$stmt->bind_param('s', $SID);
$stmt->execute();
}
public function session_gc() {
$stmt = $this->_dblink->prepare("
DELETE FROM {$this->_sessionTable} WHERE UNIX_TIMESTAMP(expiration) < " .
UNIX_TIMESTAMP(NOW()) - self::SESS_EXPIRE);
$stmt->execute();
}
}
?>

Thursday, 4 September 2014

PHP Sessions

An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.
A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Bore using any session variable make sure you have setup this path.
When a session is started following things happen:
  • PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
  • A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string.
  • A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.
When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.
A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.

Starting a PHP Session:

A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.
The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.
Make use of isset() function to check if session variable is already set or not.
Put this code in a test.php file and load this file many times to see the result:
<?php
   session_start();
   if( isset( $_SESSION['counter'] ) )
   {
      $_SESSION['counter'] += 1;
   }
   else
   {
      $_SESSION['counter'] = 1;
   }
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php  echo ( $msg ); ?>
</body>
</html>

Destroying a PHP Session:

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.
Here is the example to unset a single variable:
<?php
   unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables:
<?php
   session_destroy();
?>

Turning on Auto Session:

You don't need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file.

Sessions without cookies:

There may be a case when a user does not allow to store cookies on their machine. So there is another method to send session ID to the browser.
Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.
The following example demonstrates how to register a variable, and how to link correctly to another page using SID.
<?php
   session_start();

   if (isset($_SESSION['counter'])) {
      $_SESSION['counter'] = 1;
   } else {
      $_SESSION['counter']++;
   }
?>
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
   echo ( $msg );
<p>
To continue  click following link <br />
<a  href="nextpage.php?<?php echo htmlspecialchars(SID); >">
</p>
The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.

PHP: Can sessions work without cookies?

If so, how does a session work without cookies enabled in PHP?

This is a great interview question because even if you do not know the answer, you could come up with a fairly accurate answer on your own with some basic knowledge of PHP sessions and some analytical thinking. See if you can possibly think of how PHP sessions would work without cookies enabled in the browser.

The answer to how PHP sessions can work without cookies

Sessions in PHP normally do use cookies to function. But, PHP sessions can also work without cookies in case cookies are disabled or rejected by the browser that the PHP server is trying to communicate with.

How PHP sessions work without cookies

PHP does two things in order to work without cookies:
1. For every HTML form that PHP finds in your HTML code (which of course can be part of a PHP file), PHP will automatically add a hidden input tag with the name PHPSESSID right after the <form> tag. The value of that hidden input tag would be whatever value PHP assigns your session ID. So, for example, the hidden input could look something like this:
<form>

<input type="hidden" name="PHPSESSID" value="12345678" >

</form>

This way, when the form is submitted to the server, PHP will be able to retrieve the session identifier from the form and will know who it is communicating with on the other end, and will also know which session to associate the form parameters with if it is adding the form parameters to the PHP session.
2. PHP will find all the links in your HTML code, and will modify those links so that they have a GET parameter appended to the link itself. That GET parameter will also have the name of PHPSESSID, and the value will of course be the unique session identifier – so the PHP session ID will basically be a part of the URL query string.
So, for example, if your code has a link that originally looks like this:
<a href="http://www.example.com">Go to this link><a/>
When modified by PHP to include the session ID, it could look something like this:
<a href="http://www.example.com?PHPSESSID=72aa95axyz6cd67d82ba0f809277326dd">Go to this link</>

PHPSESSID can have it’s name changed in php ini file

Note that we said PHPSESSID is the name that will be used to hold the PHP session value. The name PHPSESSID can actually be changed to whatever you want if you modify the session.name value in the php.ini file.

What is a disadvantage of using PHP sessions without cookies enabled?

A disadvantage is that using PHP sessions without cookies is the fact that if you share a URL that has the PHP session ID appended to it with someone else, then they could potentially use the same exact session that you were using. It also opens you up to session hijacking – where a user’s session is deliberately stolen so that a hacker can impersonate you and do some damage.

PHP: What’s the difference between a cookie and a session in PHP?

PHP sessions improve upon cookies because they allow web applications to store and retrieve more information than cookies. PHP sessions actually use cookies, but they add more functionality and security.

Sessions store data on the server, not on the browser like cookies

The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser. Sessions use a session identifier to locate a particular user’s session data. This session identifier is normally stored in the user’s web browser in a cookie, but the sensitive data that needs to be more secure — like the user’s ID, name, etc. — will always stay on the server.

Sessions are more secure than cookies

So, why exactly should we use sessions when cookies work just fine? Well, as we already mentioned, sessions are more secure because the relevant information is stored on the server and not sent back and forth between the client and server. The second reason is that some users either turn off cookies or reject them. In that scenario, sessions, while designed to work with a cookie, can actually work without cookies as a workaround, as you can read about here: Can PHP sessions work without cookies?.

Sessions need extra space, unlike cookies


PHP sessions, unlike cookies which are just stored on the user’s browser, need a temporary directory on the server where PHP can store the session data. For servers running Unix this isn’t a problem at all, because the /tmp directory is meant to be used for things like this. But, if your server is running Windows and a version of PHP earlier than 4.3.6, then the server will need to be configured – here is what to do: Create a new folder on your Windows server – you can call it something like C:\temp. You want to be sure that every user can read and write to this folder. Then, you will need to edit your php.ini file, and set the value of session.save_path to point to the folder which you created on the Windows server (in this case, that folder is under C:\temp). And finally, you will need to restart your web server so that the changes in the php.ini file take effect.

Sessions must use the session_start function

A very important thing to remember when using sessions is that each page that will use a session must begin by calling the session_start() function. The session_start() function tells PHP to either start a brand new session or access an existing one.

How session_start in PHP uses cookies

The first time the session_start() function is used, it will try to send a cookie with a name of PHPSESSID and a value of something that looks like a30f8670baa8e10a44c878df89a2044b – which is the session identifier that contains 32 hexadecimal letters. Because cookies must be sent before any data is sent to the browser, this also means that session_start must be called before any data is sent to the Web browser.

Registering values to the session

After the session_start function is called, values can be registered to the session using the $_SESSION associative array. This is what it would look like:
   $_SESSION['name'] = 'Jack';
   $_SESSION['last_name'] = 'Lopez';