Jacques Koekemoer
Jacques Koekemoer

Reputation: 1414

php session variables are not being set

i have this php code that on successful login is supposed to set my session "valid" variable to true sniplet:

    if($row['c']>=1)
    {
     session_name($_SERVER['REMOTE_ADDR']);
     session_start();
     $_SESSION['valid']='true';
     echo "Home.php";
    } 
else 
    {echo "/";};
};

and then when the next page loads i check if the variable isset using (sniplet:)

    session_name($_SERVER['REMOTE_ADDR']);
    session_start();
    if($_SESSION['valid']==true)
     {echo "i am valid";}
    else
     {echo "i am invalid";};

but it keeps saying the page is invalid, even if it did redirect to it as a valid page

Edited: Everyone noticed this part of the code: $_SESSION['valid']='true'; and I appologise, i had retyped the code instead of copying it. My original code didnt have the quotation marks. The but it did help seeing as the session id cant contain numbers and an IP Address will have all numbers

Upvotes: 0

Views: 1736

Answers (5)

Pinke Helga
Pinke Helga

Reputation: 6702

There are situations, in which you need to implement a solution supporting periods in session names. E.g. I ran into a similar issue. I had to create a PHP page emulating the exact behavior of an ASP page to stay compatible with customer's external hardcoded frontend. In the given request header a cookie name ASP.NET_SessionId was present.

If someone else gets into similar constraints, here is a workaround.

After some research and testing, I came to the result, that the reason for the misbehavior is, that $_COOKIE does not contain the correct keys when there are special characters in the cookie name.

<?php session_start (['name' => 'ASP.NET_SessionId']); ?>
<html>
<head><title></title><meta charset="UTF-8"></head>
<body>
  <pre><?php
    //echo implode("\n", apache_request_headers());
    foreach (apache_request_headers() as $header => $value)
      echo "$header: $value" . PHP_EOL;
    echo "\n";
    var_dump($_COOKIE);
    ?></pre>
</body>
</html>

Output:

Host: example.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Cookie: ASP.NET_SessionId=31run6vlfk69j0ni9l02fad82u
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0

array(1) {
  ["ASP_NET_SessionId"]=>
  string(26) "31run6vlfk69j0ni9l02fad82u"
}

You get a similar output on the second request. The session id is changing with each request, since the default session handler does not recognize the session name properly. Unfortunely neither an error is thrown nor any notification is logged.

We could write our own session handler by implementing the SessionHandlerInterface and fetching the raw cookie data overriding the given precalculated session id when the session already exists.

However, I've chosen a quick'n'dirty workaround. The default session handler apparently just evaluates the $_COOKIES variable (or relies on the same generation algorithm). Actually the $_COOKIE variable is an associative array, which can have arbitrary strings including blanks, periods etc. as keys. We can overwrite the $_COOKIE variable at runtime as well.

<?php
  $raw_cookies = apache_request_headers()['Cookie'];
  $cookies     = preg_split('/;\s*/', $raw_cookies);
  $_COOKIE     = [];

  foreach ($cookies as $cookie)
  {
    list($k, $v) = explode('=', $cookie, 2);
    $_COOKIE[$k] = $v;
  }

  session_start (['name' => 'ASP.NET_SessionId']);
?>
<html>
<head><title></title><meta charset="UTF-8"></head>
<body>
  <pre><?php var_dump($_COOKIE); ?></pre>
</body>
</html>

Output:

array(1) {
  ["ASP.NET_SessionId"]=>
  string(26) "jqf97quci4sh6k0n4p59b3d18n"
}

Now the session id remains stable and values in $_SESSION are restored after each request.

Note that apache_request_headers() is a specific function to support Apache web servers. There should be functions to support alternative servers as well.

EDIT: On my Apache server I have found the raw cookies string also in $_SERVER[HTTP_COOKIE'].

Upvotes: 0

Nolan Knill
Nolan Knill

Reputation: 499

So I was looking into the session_name() on php.net, and I saw the following warning and comment:

Warning The session name can't consist of digits only, at least one letter must be present. Otherwise a new session id is generated every time.

Comment: if you try to name a php session "example.com" it gets converted to "example_com" and everything breaks. don't use a period in your session name.

Warning:http://www.php.net/manual/en/function.session-name.php

Comment Source:http://www.php.net/manual/en/function.session-name.php#86000

Upvotes: 3

Scott Helme
Scott Helme

Reputation: 4799

session_name($_SERVER['REMOTE_ADDR']);

From the docs: "It should contain only alphanumeric characters;" http://php.net/manual/en/function.session-name.php

$_SERVER['REMOTE_ADDR']

From the docs: "The IP address from which the user is viewing the current page." http://php.net/manual/en/reserved.variables.server.php

Valid characters are only a-z, A-Z and 0-9 but an IP address will contain periods/dots.

Edit "A valid variable name starts with a letter or underscore" http://php.net/manual/en/language.variables.basics.php This will also cause an IP address as the session name to be problematic. End Edit

Also;

This:

$_SESSION['valid']='true';

Should be this:

$_SESSION['valid']= true; <-- lack of single quotes

Try that and let me know!

Upvotes: 1

mishu
mishu

Reputation: 5397

Even if a few of us noticed that the comparison is not the problem and that the session name might be in fact an issue I am adding this answer just for an addition.

Please note that this is not the solution to the problem, others already discussed this, including me in a comment.

I just want to say that even if that was possible or if you would apply a transformation like removing the dots and adding some letters as a prefix I still find this a bad idea.

The session name is used for the cookie stored in the client's browser and it is used to recognize him on subsequent calls. If you are using the ip in the session name you are locking the session on the ip address and I can think of at least two cases when this is not a good idea:

  1. if I am using my phone to browse your site and walking around switching from a connection to a wifi network to the service provider data package my ip will change and you will log me out
  2. some (I think that most, I might be wrong) ISPs don't provide a fixed IP addresses to customers so with each restart to my router my IP will change, so I will be logged out again

Upvotes: 2

Amal
Amal

Reputation: 76666

You're setting your $_SESSION variable to 'True' (a string), and in your if statement you're checking if it is True (boolean). They are not the same.

Change

$_SESSION['valid']='true';

to

$_SESSION['valid']= True;

Hope this helps!

Upvotes: 1

Related Questions