Solved

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

Posted on 2013-06-27
4
333 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 39281341
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 56

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 39281355
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
ID: 39281417
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
ID: 39281421
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
A quick Powershell script I wrote to find old program installations and check versions of a specific file across the network.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

749 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