?
Solved

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

Posted on 2013-06-27
4
Medium Priority
?
341 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 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 60

Accepted Solution

by:
Julian Hansen earned 2000 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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

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

These days socially coordinated efforts have turned into a critical requirement for enterprises.
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…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Suggested Courses
Course of the Month16 days, 2 hours left to enroll

850 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