Admin username/password isn't working for PHP
Asked Answered
P

7

11

So I am currently taking a course in PHP Programming and I have finally gotten into the art of Authentication and Authorization.

So in the book, we started by restricting the page that grants access to all the accounts where you can update and delete all of them. We started by defining the constants:

define('VALID_USERNAME', '');
define('VALID_PASSWORD', '');

To make it easy on myself, I just put them as empty strings.

Everything goes smoothly, the dialogue that asks for the username and password pop up. However, when I put the empty strings in, the dialogue box keeps popping up as if the password was wrong, or it just didn't take the password at all. This happens even when I define the username and password with real strings.

Here is my code for that portion:

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
    header('http/1.1 401 Unauthorized');
    header('WWW-Authenticate: Basic realm="Wonder Penguin"');
} else {
    if (($_SERVER['PHP_AUTH_USER'] != VALID_USERNAME) ||
        ($_SERVER['PHP_AUTH_PW'] != VALID_PASSWORD)) {
        header('http/1.1 401 Unauthorized');
        header('WWW-Authenticate: Basic realm="Wonder Penguin"');
    }
}

If you're wondering why I didn't use the exit() function to prevent people from hitting cancel to bypass the authentication and getting to the update page. I did that so my teacher can grade this page that I created last assignment.

How I've tired to troubleshoot:

I tested to see if I defined the valid usernames and passwords correctly by using the echo functions.

echo VALID_USERNAME;
echo VALID_PASSWORD;

And it pops up exactly what I defined it as. So in theory, I think I defined it correctly.

I tried to write the define function with single quotes, double quotes, and no quotes. The book wants me to write the function like this:

define(VALID_USERNAME, "admin");
define(VALID_PASSWORD, "password");

However, this brings up an error that I am using an undefined constant when I tried to define them right there.

var_dump($_SERVER); Results:

array(37) {

["REDIRECT_HANDLER"]=> string(23) "application/x-httpd-php"
["REDIRECT_STATUS"]=> string(3) "200"
["HTTP_HOST"]=> string(20) "patti-bee2.dcccd.edu"
["HTTP_CONNECTION"]=> string(10) "keep-alive"
["HTTP_ACCEPT"]=> string(74) "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
["HTTP_USER_AGENT"]=> string(108) "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"
["HTTP_ACCEPT_ENCODING"]=> string(17) "gzip,deflate,sdch"
["HTTP_ACCEPT_LANGUAGE"]=> string(14) "en-US,en;q=0.8"
["HTTP_COOKIE"]=> string(217) "__qca=P0-630369357-1378011844686; __utma=198331962.264424896.1377179965.1382812794.1384740700.12; __utmc=198331962; __utmz=198331962.1381981575.8.4.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
["PATH"]=> string(135) "C:\Program Files (x86)\PHP\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;c:\php;"
["SystemRoot"]=> string(10) "C:\Windows"
["COMSPEC"]=> string(27) "C:\Windows\system32\cmd.exe"
["PATHEXT"]=> string(53) ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC"
["WINDIR"]=> string(10) "C:\Windows"
["SERVER_SIGNATURE"]=> string(0) ""
["SERVER_SOFTWARE"]=> string(21) "Apache/2.2.22 (Win32)"
["SERVER_NAME"]=> string(20) "patti-bee2.dcccd.edu"
["SERVER_ADDR"]=> string(14) "144.162.99.193"
["SERVER_PORT"]=> string(2) "80"
["REMOTE_ADDR"]=> string(11) "99.7.247.36"
["DOCUMENT_ROOT"]=> string(66) "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs"
["SERVER_ADMIN"]=> string(16) "[email protected]"
["SCRIPT_FILENAME"]=> string(106) "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\Coleman\Wonder Penguin\PHP\show_all.php"
["REMOTE_PORT"]=> string(5) "54619"
["REDIRECT_URL"]=> string(40) "/coleman/wonder penguin/php/show_all.php"
["GATEWAY_INTERFACE"]=> string(7) "CGI/1.1"
["SERVER_PROTOCOL"]=> string(8) "HTTP/1.1"
["REQUEST_METHOD"]=> string(3) "GET"
["QUERY_STRING"]=> string(0) ""
["REQUEST_URI"]=> string(42) "/coleman/wonder%20penguin/php/show_all.php"
["SCRIPT_NAME"]=> string(40) "/coleman/wonder penguin/php/show_all.php"
["ORIG_SCRIPT_FILENAME"]=> string(18) "C:/PHP/php-cgi.exe"
["ORIG_PATH_INFO"]=> string(40) "/coleman/wonder penguin/php/show_all.php"
["ORIG_PATH_TRANSLATED"]=> string(106) "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\Coleman\Wonder Penguin\PHP\show_all.php"
["ORIG_SCRIPT_NAME"]=> string(16) "/php/php-cgi.exe"
["PHP_SELF"]=> string(40) "/coleman/wonder penguin/php/show_all.php"
["REQUEST_TIME"]=> int(1385432192)
}

I have pretty much copied it straight out of the book at this point. What am I doing wrong?

If you want to try it out for yourself, here is link to my site.

Proclamation answered 25/11, 2013 at 22:0 Comment(7)
I'm skeptical about this book you're using. You should definitely be defining constants using their names as strings define('VALID_USERNAME', 'admin') as you have found. Also as a code style note, consider using ' for string literals rather than ", so you don't get surprised by variables or escaped characters with `. ('` is faster in theory, anyway.) Anyway, I'm wondering what the output of var_dump($_SERVER) is. That should help you debug this. I suspect that with empty username/password, those variables aren't showing up at all.Peel
@Brad, I just tried it, and I got a mess of an error.Proclamation
That's no error, that's the debugging output you need! It's basically every variable in the $_SERVER superglobal associative array. Some servers use other names, other than PHP_AUTH_USER and PHP_AUTH_PW. I wanted to see what that output was. Can you paste it in your question?Peel
@Brad, there you go, sir.Proclamation
There is no authorization anything in $_SERVER. When you did the debugging output, did you login first? If so, Apache's CGI parameters are likely configured incorrectly somehow. Again though, try logging in first with something (not just empty strings) for username/password.Peel
@Brad, the thing is that I can't log in. The thing just loops over and over again asking for a password. I tried it with a real username and password and the same thing still happens. I have to hit the cancel button to bypass the login to get to the page and obviously that isn't acceptable in a web page.Proclamation
For a start, you need to put an exit after the header. If you don't do that then php keeps executing your script after the header command.Anselm
B
1

Use following code for best result like


define(VALID_USERNAME, "admin");
define(VALID_PASSWORD, "password");

if (($_SERVER['PHP_AUTH_USER'] != VALID_USERNAME) ||
    ($_SERVER['PHP_AUTH_PW'] != VALID_PASSWORD)) {

    header('WWW-Authenticate: Basic realm="Wonder Penguin"');
    header('HTTP/1.0 401 Unauthorized');
exit;
    }
Bowing answered 28/11, 2013 at 13:59 Comment(0)
M
0

Try this

define('VALID_USERNAME', '');
define('VALID_PASSWORD', '');

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']))
{
    header('http/1.1 401 Unauthorized');
    header('WWW-Authenticate: Basic realm="Wonder Penguin"');
    echo "Fail";
}
else
{
    if (($_SERVER['PHP_AUTH_USER'] != VALID_USERNAME) ||
        ($_SERVER['PHP_AUTH_PW'] != VALID_PASSWORD))
    {
        header('http/1.1 401 Unauthorized');
        header('WWW-Authenticate: Basic realm="Wonder Penguin"');
        echo "Fail";
    }
    else
    {
        echo "SUccess";
    }
}
Matty answered 23/12, 2013 at 9:34 Comment(0)
C
0

this kind of global variable user name and log In status is store in session so we can you globally, I prefer to store in session rather than the define this as constants

Curie answered 30/1, 2014 at 9:11 Comment(0)
F
0

I know I'm no expert or good on explaining things clearly but as far as I know the problem lies on how do use the Basic Authentication and where to put the headers of Basic Authentication (For me just don't put it redundantly.):

Here's a code that might help you play with Basic Authentication :

In containing credentials such as usernam and password. I wont suggest using define() for security purposes.

if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']))
{
   $valid_user = 'admin';
   $valid_password = 'password';
   if($_SERVER['PHP_AUTH_USER'] == $valid_user && $_SERVER['PHP_AUTH_PW'] == $valid_password)
   {
      $response = array('Response'  => true,
                        'Message'   => 'Welcome! ' . $valid_user);

      $result = json_encode($response);
      echo $result;
   }
   else
   {
      $response = array('Response'  => false,
                        'Message'   => 'User and Password does not match!');

      $result = json_encode($response);
      echo $result;
      exit();
   }
}
else
{
   header('WWW-Authenticate: Basic realm="Wonder Penguin"');
   header('HTTP/1.0 401 Unauthorized');

   $response = array('Response' => false,
                     'Message'  => '401 Unauthorized!');

   $result = json_encode($response);
   echo $result;
   exit();
}

That's all and Enjoy learning!

Fayefayette answered 6/8, 2014 at 11:59 Comment(0)
F
0

starting with php5.6 you can use const at compile time. This means you can not assign them inside conditions at run time, the way you can with define.

const VALID_USERNAME = "admin";      // global
const VALID_PASSWORD = "password";   // global

class CREDENTIALS {
    const VALID_USERNAME = "admin";     // not global
    const VALID_PASSWORD = "password";  // not global
}


echo CREDENTIALS::VALID_USERNAME;  // "admin"
echo CREDENTIALS::VALID_PASSWORD;  // "password"

if(!defined("VALID_USERNAME")){
    echo "the constant VALID_USERNAME is not defined";
}


if(isset($_SERVER['SOMETHING'])){
   const VALID_USERNAME = "admin";     // won't work
   const VALID_PASSWORD = "password";  // won't work
}

if(isset($_SERVER['SOMETHING'])){
   define("VALID_USERNAME","admin");     //  works
   define("VALID_PASSWORD","password");  // works
}

  1. Constants must be assigned a value when they are created.
  2. A constant may only be initialized with a constant value, and not with an expression.
  3. const can be used to create global constants. Such a constant is defined in the global scope and can be accessed anywhere in the script
  4. const can use within a class or interface to define a class constant or interface constant.
  5. Class constants are referenced in the same way as static properties
  6. define cannot be used for this purpose.

Or if you want to create a array

class CREDENTIALS {
    const ARR = [
        VALID_USERNAME => "admin",
        VALID_PASSWORD => "password"
    ]
}

echo CREDENTIALS::ARR['VALID_USERNAME']; // "admin",
echo CREDENTIALS::ARR['VALID_PASSWORD']; // "password"

since php7 you can now also define constants as a array

define(ARR, [
 "VALID_USERNAME" => "admin",
 "VALID_PASSWORD" => "password"
]);

echo ARR["VALID_USERNAME"]; // "admin"
echo ARR["VALID_PASSWORD"]; // "password"

if you are using namespaces, const defines constants always in the current namespace, while using define you must always use the full namespace name

namespace SOME\NAME\SPACE;

    const VALID_USERNAME = "admin";
    const VALID_PASSWORD = "password";

    define("SOME\NAME\SPACE\VALID_USERNAME", "admin");
    define("SOME\NAME\SPACE\VALID_PASSWORD", "password");
Frustrated answered 4/6, 2020 at 2:24 Comment(0)
S
-2

Thats an easy one: if your setting a username and password programmatically then try this(if using a login page!)

<?php
$username = $_POST['username'];
$password = $_POST['password'];
$cu = "admin";
$cpw = "password";
if($username = $cu && $password = $cpw){
//Code to be executed
}else{
if condition is false
}
?>
Sidewalk answered 25/11, 2013 at 22:6 Comment(2)
There is no login page... basic auth is used.Peel
And besides, you need == instead of = if you want to evaluate that they're the same, instead of simply changing $username into 'admin'Deboer
F
-2

perhaps because you are looking using OR. you are saying if the username is not valid or the password is not valid then show a 401. try making it an && instead? This way they must have the exact username and password.

if (($_SERVER['PHP_AUTH_USER'] != VALID_USERNAME) ||
    ($_SERVER['PHP_AUTH_PW'] != VALID_PASSWORD)) {
header('http/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Wonder Penguin"');
    }
Fortna answered 25/11, 2013 at 22:8 Comment(1)
"try making it an && instead? This way they must have the exact username and password." --- it's the opposite. || is used correctly there.Brandabrandais

© 2022 - 2024 — McMap. All rights reserved.