Solved

Trying to se $_COOKIE in PHP but having trouble ....

Posted on 2013-06-27
4
324 Views
Last Modified: 2013-06-27
Hey all.

I have a PHP program (PHP is not my forte) and am having trouble when trying to use a set cookie for authentication.

In the following code, the first time through the user ID and password is used to authenticate. If authenticated, a cookie is set on the user's machine.

The way it "should" work is that for future calls, the cookie should be used first to authenticate and if it's not valid, then check for user ID / password.

I have verified that the cookie is in fact being created in the correct domain, but it is not being used for authentication due to it not "being found". Again, the cookie is on my machine but the PHP code, when checking if it's "empty", does *not* find it.

In the "try" block, I've tried using the incoming id / password as well as this:

$_COOKIE['loginapp.token_key'] = $loginapp->authenticatePrincipal(
                        $_SERVER['PHP_AUTH_USER'],
                        $_SERVER['PHP_AUTH_PW'],
                        $_SERVER['HTTP_USER_AGENT'],
                        $_SERVER['REMOTE_ADDR']
                  );

If the cookie "is found", should it not use that and *not* the id / password for authentication?

Any help would be greatly appreciated.

<?php
/**
 * This file demonstrates using Atlassian loginapp for Single Sign On.
 */
header('Content-Type: application/json');
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
$loginapp_app_name = 'loginappapp';
$loginapp_app_password = 'loginapppass';
$loginapp_url = 'loginapp_url';

$loginappuserid = (isset($_REQUEST['myuserid']) ? $_REQUEST['myuserid'] : '');
$loginapppass = (isset($_REQUEST['mypassword']) ? $_REQUEST['mypassword'] : '');
$loginapptoken = (isset($_REQUEST['mytoken']) ? $_REQUEST['mytoken'] : '');

session_set_cookie_params(0, '/', '.mydomain.com');

$username = NULL;
$groups   = NULL;

.....

$is_authenticated = FALSE;
if (!empty($_COOKIE['loginapp.token_key']))      <---- although the cookie exists, this check fails
{
      // If the user already had a loginapp token, we need to verify that it's still valid
      $is_authenticated = $loginapp->isValidPrincipalToken(
            $_COOKIE['loginapp.token_key'],
            $_SERVER['HTTP_USER_AGENT'],
            $_SERVER['REMOTE_ADDR']
      );
}
if (!$is_authenticated)
{
      if (!isset($_SERVER['PHP_AUTH_USER'])) {
            header('WWW-Authenticate: Basic realm="loginapp Login"');
            header('HTTP/1.0 401 Unauthorized');
            $username = 'Forbidden';
            exit;
      }

      try
      {
                **** when using ID and password, the cookie is set ****
            $_COOKIE['loginapp.token_key'] = $loginapp->authenticatePrincipal(
                  $loginappuserid,
                  $loginapppass,
                  $_SERVER['HTTP_USER_AGENT'],
                  $_SERVER['REMOTE_ADDR']
            );

            setcookie('loginapp.token_key', $_COOKIE['loginapp.token_key'], time() + 3600, '/', '.mydomain.com');
            print 'COOKIE: '.$_COOKIE['loginapp.token_key'].'<br>';
            $is_authenticated = TRUE;
      }
      catch (Exception $e)
      {
            // I have no idea why, but instead of throwing an
            // invalid username or password exception, we get
            // an exception with the username provided if either is wrong.
            if ($e->getMessage() == $_SERVER['PHP_AUTH_USER'])
            {
                  // todo: prompt for login again
            }
            //throw $e;
            $username = 'Forbidden';
      }
}

....
0
Comment
Question by:Webspeeder
4 Comments
 
LVL 34

Expert Comment

by:gr8gonzo
Comment Utility
Add this after $is_authenticated = FALSE;

if(isset($_COOKIE["loginapp.token_key"]))
{
  echo "Cookie loginapp.token_key exists: ";
  var_dump($_COOKIE["loginapp.token_key"]);
  die();
}
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
Comment Utility
try adding this to the start of your script to see what is in $_COOKIE

print_r($_COOKIE);

or

var_dump($_COOKIE);

enclose in <pre> tags to better see the output if required.

This might shed some light
0
 

Author Closing Comment

by:Webspeeder
Comment Utility
Well, that help to fix the issue but I'm still confused.

The cookie was being set with a ".", 'loginapp.token' but when using the command you gave, it came back with loginapp_token. The period was an underscore.

I changed all the periods to underscores and now it works. On my machine, even now when looking, I see the "period" version, not the underscore. I deleted the cookie and it doesn't find it anymore.

I'll get it recreated, but if it is being set with an underscore, why does the name (in Google Chrome) show as a period?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
Also this is an age old issue

  setcookie('loginapp.token_key', $_COOKIE['loginapp.token_key'], time() + 3600, '/', '.mydomain.com');

There is NOTHING in the $_COOKIE at this point BECAUSE $_COOKIE gets its value from the REQUEST and you have not yet sent that request back to this script from the client

            print 'COOKIE: '.$_COOKIE['loginapp.token_key'].'<br>'; // empty until next time
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now