Why won't the browser receive the php session_id and session cookie?

For some reason the browser does not seem to receive the cookie set by test-from.php and redirected to test-to.php. Thus the session data is not accepted either.
I need to use session cookies as opposed to persistent cookies. The whole site is SSL. PHP is 5.3.3-7. Same result on latest versions of firefox and chrome - not tried on IE.
After testing, I know the session name is correct in test-to.php, however a different session id presents there instead of the one in test-from.php as shown in firebug. Neither the session id nor the cookie are output in test-to.php.

What do you reckon I'm doing wrong here?

php.ini:

session.use_cookies = 1
session.cookie_secure = On
session.use_only_cookies = 1
session.name = sess-name
session.auto_start = 0
session.cookie-lifetime = 0
session.cookie_path = /
session.cookie_domain = https://hostaddress/example/
session.cookie_httponly = true


test-from.php:
<?php
ob_start();

session_name();
$session_name = session_name();
session_start();
session_id();
$_SESSION['id'] = session_id();

if (ini_get("session.use_cookies"))
{
    $params = session_get_cookie_params();
    setcookie($session_name, session_id(), $params["lifetime"], $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
    $url = "https://hostaddress/example/folder/test-to.php";     // https://hostaddress/example/ is the SSL form of host address set by the web host company
    ob_end_clean();
    header("Location: $url");
    mysqli_close($dbc);
    exit();
}

ob_end_flush();
?>

Open in new window


test-to.php:
ob_start();

session_name();
session_start();
session_id();
$session_name = session_name();

if(isset($_SESSION['id']))
{
    echo "_session[id] = ".$_SESSION['id']."<br>";
}
else
{
    echo "_session[id] not set<br>";
}

if(!isset($_COOKIE[$session_name]))
{
    echo "_cookie[session_name] not set<br>";
}
else
{
    echo "_session[id] = ".$_SESSION['id']."<br>";
    echo "cookie is set<br>";
    echo "cookie = ".$_COOKIE[$session_name]."<br>";
    echo "session_name() = ".session_name()."<br>";
    echo "old session_id = ".$_SESSION['id']."<br>";
}

ob_end_flush();
?>

Open in new window


Output:

_session[id] not set
_cookie[session_name] not set


session_id()'s at the server:

sess_ah7jurbmn9151e3hbf4s2qrhsd048rq5
sess_0ed5v570grt69skl1508dpqpofpus6fn


Firebug -> Net:

GET test-from.php        302 Moved Temporarily      hostaddress      0B     IP address
Headers

Response Headers
Cache-Control      no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection      Keep-Alive
Content-Length      0
Content-Type      text/html
Date      Fri, 20 Mar 2015 20:38:08 GMT
Expires      Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive      timeout=5, max=256
Location      https://hostaddress/example/folder/test-to.php
Pragma      no-cache    Server      Apache
Set-Cookie      sess-name=ah7jurbmn9151e3hbf4s2qrhsd048rq5; path=/; domain=https://hostaddress/example/; secure; HttpOnly
sess-name=ah7jurbmn9151e3hbf4s2qrhsd048rq5; path=/; domain=https://hostaddress/example/; secure; httponly

Request Headers
Accept      text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding      gzip, deflate
Accept-Language      en-GB,en;q=0.5
Connection      keep-alive
Host      hostaddress
User-Agent      Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0


GET test-to.php      200 OK       hostaddress       143 B       IP address
Headers

Response Headers
Cache-Control      no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection      Keep-Alive
Content-Type      text/html
Date      Fri, 20 Mar 2015 20:38:08 GMT
Expires      Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive      timeout=5, max=255
Pragma      no-cache
Server      Apache
Set-Cookie      sess-name=0ed5v570grt69skl1508dpqpofpus6fn; path=/; domain=https://hostaddress/example/; secure; HttpOnly
Transfer-Encoding      chunked

Request Headers
Accept      text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding      gzip, deflate
Accept-Language      en-GB,en;q=0.5
Connection      keep-alive
Host      hostaddress
User-Agent      Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0
Torquil BeavisBusinessAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
'session_name' sets the name of the cookie, not the value which is the session_id.  The normal name of the cookie is 'PHPSESSID' and what you should normally see for a cookie is 'PHPSESSID=0ed5v570grt69skl1508dpqpofpus6fn' or something similar.
http://php.net/manual/en/function.session-name.php

And header("Location: $url"); does not 'carry' the cookies with it.

Please try the examples on this page http://php.net/manual/en/function.session-start.php and you will see how this is supposed to work.
0
Torquil BeavisBusinessAuthor Commented:
Thanks Dave. You'll see that my choice of session name is sess_name and firebug shows it being used as sess-name=ah7jurbmn9151e3hbf4s2qrhsd048rq5 in test-from and as sess-name=0ed5v570grt69skl1508dpqpofpus6fn in test-to.

I appreciate your explanations, however, I'm looking for a solution as to why the cookie and session variable are not present in test-to. Since the header doesn't carry the cookie with it, does it carry the session_id? I tried .SID but that failed. What is the standard method of having the session data and cookie received by test-to when using a redirect without the risks associated with using session.use_trans_sid?
0
Dave BaldwinFixer of ProblemsCommented:
If you run the examples on that page you will see how it is intended to work.  These are the headers I get from running the demo code.  This is running on IIS so there is always an ASPSESSIONID.  The PHP 'session_name' I use on this system is DIBSHPP4 and I set it in 'php.ini'.
http://10.202.46.40/ee2/PHPsessions/page1.php

GET /ee2/PHPsessions/page1.php HTTP/1.1
Host: 10.202.46.40
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:36.0) Gecko/20100101 Firefox/36.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://10.202.46.40/ee2/PHPsessions/
Cookie: test=999; ASPSESSIONIDQQRQQRSD=HICDFNFCOAMGDFOMNKAJHKMB
Connection: keep-alive

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.1
Date: Sat, 21 Mar 2015 00:29:26 GMT
X-Powered-By: ASP.NET, PHP/5.3.28
Connection: close
Content-Type: text/html
Set-Cookie: DIBSHPP4=2vrrh9ci17r93iqbanicahibp1; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
----------------------------------------------------------
http://10.202.46.40/ee2/PHPsessions/page2.php

GET /ee2/PHPsessions/page2.php HTTP/1.1
Host: 10.202.46.40
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:36.0) Gecko/20100101 Firefox/36.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://10.202.46.40/ee2/PHPsessions/page1.php
Cookie: test=999; ASPSESSIONIDQQRQQRSD=HICDFNFCOAMGDFOMNKAJHKMB; DIBSHPP4=2vrrh9ci17r93iqbanicahibp1
Connection: keep-alive

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.1
Date: Sat, 21 Mar 2015 00:29:31 GMT
X-Powered-By: ASP.NET, PHP/5.3.28
Connection: close
Content-Type: text/html
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
----------------------------------------------------------

Open in new window

0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Dave BaldwinFixer of ProblemsCommented:
I'm going to go run all this code on Linux/Apache in a minute and see what I get.
0
Dave BaldwinFixer of ProblemsCommented:
These are the headers from the demo pages.  Session cookie name is PHPDAVIDUBU.
http://10.202.46.38/~davidi/dibtest/page1.php

GET /~davidi/dibtest/page1.php HTTP/1.1
Host: 10.202.46.38
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://10.202.46.38/~davidi/dibtest/
Cookie: __utma=88090395.247860405.1386828218.1386828218.1386828218.1
Connection: keep-alive

HTTP/1.1 200 OK
Date: Sat, 21 Mar 2015 01:06:56 GMT
Server: Apache/2.2.14 (Ubuntu) mod_wsgi/2.8 Python/2.6.5 PHP/5.3.2-1ubuntu4.29 with Suhosin-Patch
X-Powered-By: PHP/5.3.2-1ubuntu4.29
Set-Cookie: PHPDAVIDUBU=52edeef523b6e9cc18c4ab8252024538; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 135
Keep-Alive: timeout=15, max=93
Connection: Keep-Alive
Content-Type: text/html
----------------------------------------------------------
http://10.202.46.38/~davidi/dibtest/page2.php

GET /~davidi/dibtest/page2.php HTTP/1.1
Host: 10.202.46.38
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://10.202.46.38/~davidi/dibtest/page1.php
Cookie: __utma=88090395.247860405.1386828218.1386828218.1386828218.1; PHPDAVIDUBU=52edeef523b6e9cc18c4ab8252024538
Connection: keep-alive

HTTP/1.1 200 OK
Date: Sat, 21 Mar 2015 01:07:05 GMT
Server: Apache/2.2.14 (Ubuntu) mod_wsgi/2.8 Python/2.6.5 PHP/5.3.2-1ubuntu4.29 with Suhosin-Patch
X-Powered-By: PHP/5.3.2-1ubuntu4.29
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 87
Keep-Alive: timeout=15, max=92
Connection: Keep-Alive
Content-Type: text/html
----------------------------------------------------------

Open in new window


These are from your pages.
http://10.202.46.38/~davidi/dibtest/test-from.php

GET /~davidi/dibtest/test-from.php HTTP/1.1
Host: 10.202.46.38
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://10.202.46.38/~davidi/dibtest/
Cookie: __utma=88090395.247860405.1386828218.1386828218.1386828218.1; PHPDAVIDUBU=52edeef523b6e9cc18c4ab8252024538
Connection: keep-alive

HTTP/1.1 302 Found
Date: Sat, 21 Mar 2015 01:13:56 GMT
Server: Apache/2.2.14 (Ubuntu) mod_wsgi/2.8 Python/2.6.5 PHP/5.3.2-1ubuntu4.29 with Suhosin-Patch
X-Powered-By: PHP/5.3.2-1ubuntu4.29
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: PHPDAVIDUBU=52edeef523b6e9cc18c4ab8252024538; path=/
Location: test-to.php
Content-Length: 165
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html
----------------------------------------------------------
http://10.202.46.38/~davidi/dibtest/test-to.php

GET /~davidi/dibtest/test-to.php HTTP/1.1
Host: 10.202.46.38
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://10.202.46.38/~davidi/dibtest/
Cookie: __utma=88090395.247860405.1386828218.1386828218.1386828218.1; PHPDAVIDUBU=52edeef523b6e9cc18c4ab8252024538
Connection: keep-alive

HTTP/1.1 200 OK
Date: Sat, 21 Mar 2015 01:13:56 GMT
Server: Apache/2.2.14 (Ubuntu) mod_wsgi/2.8 Python/2.6.5 PHP/5.3.2-1ubuntu4.29 with Suhosin-Patch
X-Powered-By: PHP/5.3.2-1ubuntu4.29
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 283
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Content-Type: text/html
----------------------------------------------------------

Open in new window

0
Ray PaseurCommented:
TL;DR but I'll try this later when I have a chance.  You mentioned that you needed a session cookie and could not use a persistent cookie.  That kind of statement makes me wonder "why" since the mechanisms are exactly the same - only the cookie expiration date is different.  For cookies to work, your client machine must accept and return the cookies.  Since cookie acceptance is 100% under the control of the client, there is a possibility that the client does not store the cookies.  This has often been a point of confusion for developers, and since I don't really know your experience level on these things, please let me refer you to an article that shows most of the things you need to know to get up and running with PHP sessions.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11909-PHP-Sessions-Simpler-Than-You-May-Think.html
0
Ray PaseurCommented:
These scripts appear to work correctly for me, on my server, when I set my browser to accept cookies.  I made only minimal changes, both lines marked in the "from" script.  Overall, I think these scripts are doing a lot of non-value-added work that can be simplified.  I'll show you the simplified script in the next post.

http://iconoun.com/demo/temp_krotb_to.php
<?php // demo/temp_krotb_from.php

/**
 * See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28641039.html
 */
error_reporting(E_ALL);

// SAMPLE CODE FROM E-E FOLLOWS
ob_start();

session_name();
$session_name = session_name();
session_start();
session_id();
$_SESSION['id'] = session_id();

if (ini_get("session.use_cookies"))
{
    $params = session_get_cookie_params();
    setcookie($session_name, session_id(), $params["lifetime"], $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
    $url = "temp_krotb_to.php"; // ************* MODIFIED
    ob_end_clean();
    header("Location: $url");
    // mysqli_close($dbc);      ******************** MODIFIED - $dbc is an undefined variable and throws a message
    exit();
}

ob_end_flush();

Open in new window

http://iconoun.com/demo/temp_krotb_to.php
<?php // demo/temp_krotb_to.php

/**
 * See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28641039.html
 */
error_reporting(E_ALL);

// SAMPLE CODE FROM E-E FOLLOWS
ob_start();

session_name();
session_start();
session_id();
$session_name = session_name();

if(isset($_SESSION['id']))
{
    echo "_session[id] = ".$_SESSION['id']."<br>";
}
else
{
    echo "_session[id] not set<br>";
}

if(!isset($_COOKIE[$session_name]))
{
    echo "_cookie[session_name] not set<br>";
}
else
{
    echo "_session[id] = ".$_SESSION['id']."<br>";
    echo "cookie is set<br>";
    echo "cookie = ".$_COOKIE[$session_name]."<br>";
    echo "session_name() = ".session_name()."<br>";
    echo "old session_id = ".$_SESSION['id']."<br>";
}

ob_end_flush();

Open in new window


Outputs:
_session[id] = e9bc7aa28f584e2846a5e2f67f0aa6ed
_session[id] = e9bc7aa28f584e2846a5e2f67f0aa6ed
cookie is set
cookie = e9bc7aa28f584e2846a5e2f67f0aa6ed
session_name() = PHPSESSID
old session_id = e9bc7aa28f584e2846a5e2f67f0aa6ed

Open in new window

0
Ray PaseurCommented:
Here is a simplified example.  In most correctly configured PHP installations, this is everything you ever need to use the session.

http://iconoun.com/demo/temp_simple_krotb_from.php
<?php // demo/temp_simple_krotb_from.php

/**
 * See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28641039.html
 */
error_reporting(E_ALL);


// ALWAYS START THE SESSION ON EVERY REQUEST WITHOUT EXCEPTION
session_start();

// DO YOUR PROCESSING LOGIC TO GENERATE THE INFORMATION
// THAT NEEDS TO BE PASSED FROM REQUEST TO REQUEST IN THE
// PHP SESSION
$_SESSION['cheese'] = 'cheddar';


// REDIRECT TO A NEW PAGE THAT WILL USE THE SESSION DATA
// NOTE WE USE DIE TO EXIT THIS SCRIPT IMMEDIATELY AFTER THE
// REDIRECT HEADER, SO THE SCRIPT DOES NOT EXECUTE OTHER CODE
// WHILE WAITING FOR THE BROWSER TO GO TO THE NEW LOCATION
header("Location: temp_simple_krotb_to.php");
die();

Open in new window


http://iconoun.com/demo/temp_simple_krotb_to.php
<?php // demo/temp_simple_krotb_to.php

/**
 * See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28641039.html
 */
error_reporting(E_ALL);


// ALWAYS START THE SESSION ON EVERY REQUEST WITHOUT EXCEPTION
session_start();


// DO THE PROCESSING LOGIC THAT CONSUMES THE INFORMATION
// THAT WAS PASSED FROM AN EARLIER REQUEST IN THE PHP SESSION
var_dump($_SESSION);

Open in new window

0
Torquil BeavisBusinessAuthor Commented:
Thank you both. You have both verified that the session/cookie code works. Here is the output I get for the examples page1 and page2 that you recommended Dave, using firebug:

GET page2.php
hostname

Headers
Response headers

Cache-Control	no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection	Keep-Alive
Content-Type	text/html
Date	Sat, 21 Mar 2015 13:52:08 GMT
Expires	Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive	timeout=5, max=256
Pragma	no-cache
Server	Apache
Set-Cookie	sess_name=j1oknqureqeb2s1b8invbom103pb4t2n; path=/; domain=https://hostname/example/; secure; HttpOnly
Transfer-Encoding	chunked

Request headers
Accept	text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding	gzip, deflate
Accept-Language	en-GB,en;q=0.5
Connection	keep-alive
Host	hostname
Referer	https://hostname/example/folder/page1.php
User-Agent	Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0

Open in new window


And this is the output:
Welcome to page #2
Notice: Undefined index: favcolor in /absoluteaddress/page2.php on line 8 Notice: Undefined index: animal in /absoluteaddress/page2.php on line 9 Notice: Undefined index: time in /absoluteaddress/page2.php on line 10 1969 12 31 19:00:00
page 1

Open in new window


It seems to me that since this test fails on the web host server that I use, and also that my 2 pages also fail yet succeed with both of your servers, that there may either be an issue with my php.ini or the session files/management system on the server.

What do you think? What should I try next?
0
Ray PaseurCommented:
Run this script, shown here in its entirety, and look for the session settings.
<?php phpinof();

Open in new window

You may want to post those here.  You may also want to contact your web hosting provider because a working PHP session is kind of a minimum qualification in the "merchantability" category for web hosting services!  In other words, let them know that they have a problem and you need them to diagnose and fix it.  If they can't do that immediately, get another host.
0
Ray PaseurCommented:
Here's my output.  PHP 5.4.37.  Yours should look pretty close to this.
screen capture of phpinfo() session
0
Ray PaseurCommented:
... but that said, I'm a little concerned about this part:
Notice: Undefined index: favcolor in /absoluteaddress/page2.php on line 8 ...

This was not part of the first set of scripts posted here.  Perhaps there has been a change in the code that we did not see in this dialog?
0
Torquil BeavisBusinessAuthor Commented:
Here's the phpinfo.php session data:

session
Session Support 	enabled
Registered save handlers 	files user
Registered serializer handlers 	php php_binary wddx

Directive	Local Value	Master Value
session.auto_start	Off	Off
session.bug_compat_42	Off	Off
session.bug_compat_warn	Off	Off
session.cache_expire	180	180
session.cache_limiter	nocache	nocache
session.cookie_domain	https://hostname/example/	https://hostname/example/
session.cookie_httponly	On	On
session.cookie_lifetime	0	0
session.cookie_path	/	/
session.cookie_secure	On	On
session.entropy_file	no value	no value
session.entropy_length	0	0
session.gc_divisor	100	100
session.gc_maxlifetime	7200	7200
session.gc_probability	1	1
session.hash_bits_per_character	5	5
session.hash_function	1	1
session.name	sess_name	sess_name
session.referer_check	no value	no value
session.save_handler	files	files
session.save_path	/absoluteaddress/sessions	/absoluteaddress/sessions
session.serialize_handler	php	php
session.use_cookies	On	On
session.use_only_cookies	On	On
session.use_trans_sid	1	1

Open in new window

Notice anything that needs adjusted?
0
Torquil BeavisBusinessAuthor Commented:
PHP 5.3.3-7

No change in the http://php.net/manual/en/function.session-start.php page1.php and page2.php examples as advised by Dave. Apologies; I should have made this clear before ;)
0
Ray PaseurCommented:
Wow - that looks really out of date.  What version / release of PHP are you running?  Current versions are documented on PHP.net.  You should be at PHP 5.4.39, or 5.5.23, or better yet 5.6.7.

The things that get my attention (might not be "wrong," but they're not settings that are normally used)...

session.cookie_domain
session.cookie_httponly
session.cookie_secure
session.gc_maxlifetime
session.name
session.save_path

Here's a simple test that I've used in the past to verify a working PHP session.  Install it and run it exactly as-is and see if it works in a sensible way.  If the counter does not appear to be making sense, call your hosting company.  You should not have to debug something like this -- it's a basic part of the PHP installation and it should "just work."

<?php // demo/session_test.php

/**
 * Demonstrate how PHP sessions work
 * Ref: http://php.net/manual/en/function.session-start.php
 * Ref: http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11909.html
 */
error_reporting(E_ALL);

// START THE SESSION (DO THIS FIRST, UNCONDITIONALLY, IN EVERY PHP SCRIPT ON EVERY PAGE)
session_start();

// INITIALIZE THE SESSION ARRAY TO SET A DEFAULT VALUE
if (empty($_SESSION["counter"])) $_SESSION["counter"] = 1;

// SEE IF THE CORRECT SUBMIT BUTTON WAS CLICKED
if (isset($_POST['bump']))
{
    // ADD ONE TO THE COUNTER
    $_SESSION['counter']++;
}

// RECOVER THE CURRENT VALUE FROM THE SESSION ARRAY
$counter = $_SESSION['counter'];


// END OF PROCESSING SCRIPT - CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<html>
<head>
<title>Session Test</title>
</head>
<body>
Currently, SESSION["counter"] contains: $counter<br/>
<form method="post">
<input type="submit" value="increment this counter" name="bump"  />
<input type="submit" value="leave my counter alone" name="keep" />
</form>
</body>
</html>
ENDFORM;

echo $form;

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Torquil BeavisBusinessAuthor Commented:
PHP Version 5.3.3-7.6+hw2
I'm on a shared server - so maybe they keep it out of date to encourage a move to a managed server!

session.cookie_domain  -> I set this to prevent it showing on the exchange
session.cookie_httponly   -> for security (in my main app)
session.cookie_secure   -> SSL (whole site)
session.gc_maxlifetime    -> left over from before I moved the session folder
session.name  -> I set this to prevent it showing on the exchange
session.save_path   -> I set this to prevent it showing on the exchange

I ran the session_test.php and after clicking 'increment' the counter changed to 2. From the script it seems that if I select 'increment' again, it should go to 3. It did not; it stayed at 2 no matter how many times I 'incremented'.
I checked my session file and it shows a new session id each time I hit 'increment'.

Does this mean the sessions are not working? Yet the first hit seems to know the $_SESSION value of 1.
0
Ray PaseurCommented:
Yes, it means the sessions are not working.  For a first try, you might revert everything back to the default values that come with the standard installation of PHP.  See if that works.  Then if it does, it's not your host's problem.  If it does not work with the standard settings, your host should fix it.  

But if it works with the standard settings and does not work with your settings, you might want to ask yourself if you really need these custom settings.  Almost nobody changes the standard settings for the PHP session handler, so if there is a particular element of your software design that absolutely requires changes in the PHP session handler -- well, you might want to rethink that part of your design.  The standard settings are well understood and work correctly in literally millions of web sites.  As a general rule, the less you change in the standard PHP settings, the better off you'll be.
0
Torquil BeavisBusinessAuthor Commented:
Very good. I've already raised a ticket with my host, and they generally get back within 6-24 hours. Since I don't want to cause any changes to confuse them, I'll wait till they get back. If they say it's my issue, I'll do exactly as you say. I'll post the results either way.
0
Torquil BeavisBusinessAuthor Commented:
Here's the reply from the web host support - and the sessions now work:

"Our Administrators fixed the issue with the connection between the two pages:
/web/nm-app/htdocs/page1.php
/web/nm-app/htdocs/page2.php
They had to change 'session_cookie_domain' in your php.ini file. It needed to be empty."

When I check the value of $params['domain'], it is indeed blank. My understanding is that 'empty' accepts cookies from all domains. Is this a security risk?
0
Dave BaldwinFixer of ProblemsCommented:
'session_cookie_domain' is empty on all 3 of my hosting accounts and on 4 different customer accounts on different hosting companies.  More info here: http://php.net/manual/en/session.configuration.php#ini.session.cookie-domain
0
Torquil BeavisBusinessAuthor Commented:
This is a high security site. I've read the php.net on it, yet fail to understand the security implications of the empty value as opposed to non-empty values.
0
Ray PaseurCommented:
Let's step back a little bit.  If you're not 100% familiar with the Client/Server protocol, please familiarize yourself with this article.  You'll need to know this stuff if you're going to build web applications.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html

Here is a timeline of requests and responses in a typical browser interaction.

1. The browser makes a GET-method request to the server, probably because a (human) client typed a URL into the browser address bar, or clicked a link to the web page on the server.

2. The server makes a response and sends it to the browser.  This probably includes a web page, and may include cookies.  At this point the server and browser are disconnected.  If cookies are included in the response, the browser stores the cookies.

3. The browser makes another request to the server.  This time, it has cookies from the earlier response, so it sends the cookies back to the server.

4. The server, upon receiving a request with cookies, can recognize that the client had visited earlier.  If the data in the cookie contains something meaningful such as a PHP session ID, the server can look up the session and find whatever data it had stored about the client.

That's about it - HTTP is a stateless protocol, and the server can only know what the browser tells it via the request.  Each request is independent, atomic, complete and stateless.  If the request has cookies, the server can make it look like the server really knows a lot more, but in reality, its knowledge of the client is predicated on the cookies.  If the client does not send the cookies (perhaps they expired or were deleted) then the server will see the client as a net-new visitor to the site.  In the case of PHP sessions, the session will be lost if the cookies are not returned.

Does this help?  Issues related to security have nothing to do with the settings that are causing you trouble with your sessions.  For guidance on PHP security you might look to OWASP.  But first, take in the guidance on php.net.
http://php.net/manual/en/security.php
0
Dave BaldwinFixer of ProblemsCommented:
I suspect that the 'empty value' lets the PHP session_start routine put in the correct domain name and method.  I don't know of any reason for that setting to be there anyway.  When it comes to cookies, browser security is more important.  Browsers won't let you set a cookie from a different domain than the one that the page came from.  That's why tracking scripts from Google and other marketers have to run inside your page.
This is a high security site.
I'd be curious why you would say that but you probably can't tell me.

I have measures in place that tell me when people are trying to break into the sites I manage, especially thru the databases and forms.  #1 is saving all the supposed form submissions so I can go see what people are trying to do.  I missed one last month because I was not filtering for the referrer and they were able to submit 38,000 requests in an attempt to break in.  They were not able to break in because I was filtering the data well enough, I just needed to make sure they couldn't directly post to the page like they had been doing.  Now they can't do that anymore.  One more hole plugged.

If you are not tracking what people are trying to do, then your security is fairly limited.  The thing about 'session_cookie_domain' being blank is irrelevant.
0
Dave BaldwinFixer of ProblemsCommented:
My understanding is that 'empty' accepts cookies from all domains.
Just noticed this.  PHP on the server does not Accept cookies from Any domains.  'session_cookie_domain' is about Setting cookies with PHP, in particular the session id cookie.
0
Ray PaseurCommented:
Cookies are sent by the server to the browser.  The browser will only return cookies to the server (domain) that sent them.  There are no exceptions.  It really is simpler than it seems!
0
Torquil BeavisBusinessAuthor Commented:
Guys, thank you very much for your advice and guidance. I've read tomes on security, and the more I read the more I realize how little I know ;)  Of course I've implemented a number of security features, yet there are always more. I'm impressed with my first visit to the Exchange and know it will be regular.
Now, to work out how to split the credits .. :)
0
Ray PaseurCommented:
Good, I'm glad it was helpful to you!  Split points any way you want - I already have quite a few :-)
0
Dave BaldwinFixer of ProblemsCommented:
Same here, however you want.
0
Torquil BeavisBusinessAuthor Commented:
I'm impressed with the calibre of expertise on this site. I've pained over forums for too long, waiting for eons for some responses. You guys were fast, took time to explain behind the issue, and offered tests to discover the actual issue. Much obliged. Now for the beta test :)
0
Dave BaldwinFixer of ProblemsCommented:
You're welcome, glad to help.
0
Ray PaseurCommented:
^^ What Dave said :-)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.