?
Solved

use of undefined constant in authentication script

Posted on 2005-03-17
15
Medium Priority
?
927 Views
Last Modified: 2013-12-12
I'm having a problem with a authentication script that i found on here,
which looks good, but for some reason its giving me the following errors

Notice: Use of undefined constant username - assumed 'username' in /pathto/authenticate.php on line 64

Notice: Undefined index: username in /pathto/authenticate.php on line 64

Notice: Use of undefined constant action - assumed 'action' in /pathto/authenticate.php on line 66

Notice: Use of undefined constant username - assumed 'username' in /pathto/authenticate.php on line 5

Notice: Use of undefined constant password - assumed 'password' in /pathtoauthenticate.php on line 10

Notice: Use of undefined constant username - assumed 'username' in /pathto/authenticate.php on line 15

Notice: Use of undefined constant username - assumed 'username' in /pathto/authenticate.php on line 15
Sorry. Authentication failed!


when i try to use a u/p which i have in the database.

this is the code that i'm using.


<?
  session_start (); // Start the session variable

  function authenticate () {  // checks the username and password in the database mentioned below
      $_POST[username] = trim ($_POST[username]);
      if ($_POST[username] != "") {
mysql_connect('***','***','***') or die (mysql_error());    // Enter your DB details here :)
          mysql_select_db('***') or die (mysql_error());// Enter your database name :)
          $handle = mysql_query("SELECT * FROM `authenticate_users` WHERE `username` = '".$_POST[username]."' AND `password` = MD5('".$_POST[password]."');");
          $results = mysql_fetch_assoc($handle);
      } else {
          $_POST[username] = 'invalid';
      }
      if ($results[username] != $_POST[username]) {
          # authentication failed, dont add a cookie, redisplay login with a message
          echo "Sorry. Authentication failed!";
          showlogin ();
      } else {
          # authentication was successful, add a cookie and then refresh!
          session_register(username);
          $_SESSION[username] = $_POST[username];
          echo "<script language=JavaScript>document.location=\"".$_SERVER["PHP_SELF"]."\";</script>";
      }
  }

  function styles () {            // Show the style information for the login form
      echo "
         <style>
         body, td, input {
             font-size:9pt;
             font-family:lucida sans unicode, verdana, tahoma, arial, sans;
         }
         </style>
      ";
  }

  function showlogin() {         // Show the login form
      styles();
      echo "
         <title>Authentication Required!</title>
         <center>
         <u>This Page Requires Authentication</u>
         <table>
         <form action=".$_SERVER["PHP_SELF"]." method=post>
         <input type=hidden name=action value=authenticate>
         <tr><td>Username:</td><td><input name=username></td></tr>
         <tr><td>Password:</td><td><input name=password type=password></td></tr>
         <tr><td colspan=2 align=right><input type=submit value=\"Log In\"></td></tr>
         </table></form>
      ";
      exit;
  }

  function logout () {          // Close the session variable
      session_destroy();
      echo "<script language=JavaScript>document.location=\"".$_SERVER["PHP_SELF"]."\";</script>";
  }

  #####################
  ### Decision Tree ###
  #####################

  if (!$_SESSION[username]) {
      #user's not logged in
       if ($_REQUEST[action] == 'authenticate') {authenticate();}
       else {showlogin();}
  }
  elseif ($_REQUEST[action] == 'logout') {logout();}
  else {echo "<a href=\"".$_SERVER["PHP_SELF"]."?action=logout\">Log Out</a><br>";}  // customise this with your own logout bar. If you want to have their username listed in here, use $_SESSION[username]

?>
0
Comment
Question by:paulp75
[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
  • 8
  • 7
15 Comments
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13572356
Notice errors are not actually errors. If you know what you are doing, you can supress the error in php.ini error_reporting setting. ( http://www.php.net/error_reporting ).

To avoid notice errors, change ALL your POST, SESSION variables within quotes.

Example, Change :  $_POST[username]  to this : $_POST['username']
0
 
LVL 6

Author Comment

by:paulp75
ID: 13572421
thanks for that.
i changed it.
it doesnt have the errors now,
but its still not logging me in.
wierd
0
 
LVL 6

Author Comment

by:paulp75
ID: 13572467
and the username and password are definately in the database.
should these be set as TEXT.
thats what i created username and password in the database as.
can't think of anythink else that could be wrong here
thanks
0
Independent Software Vendors: 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!

 
LVL 32

Expert Comment

by:ldbkutty
ID: 13572496
Many pitfalls in your code, I changed the function to this :

// checks the username and password in the database mentioned below
function authenticate ()
{
      $link = mysql_connect('***','***','***') or die (mysql_error());    // Enter your DB details here :)
      mysql_select_db('***') or die (mysql_error());// Enter your database name :)

      if (trim($_POST['username']) != "") {
            $handle = mysql_query("SELECT * FROM `authenticate_users` WHERE `username` = '" . $_POST['username'] . "' AND `password` = MD5('" . $_POST['password'] . "')") or die("Sql error: " . mysql_error());
            if(mysql_num_rows($handle) < 1) {
                  # authentication failed, dont add a cookie, redisplay login with a message
                  echo "Sorry. Authentication failed!";
                  showlogin ();
            }
            else {
                  # authentication was successful, add a cookie and then refresh!
                  session_register('username');
                  $_SESSION['username'] = $_POST['username'];
                  echo "<script language=JavaScript>document.location=\"" . $_SERVER["PHP_SELF"] . "\";</script>";
            }
      }
}

Try this. If this doesn't works, try running the query in your phpmyadmin or sql console.
0
 
LVL 6

Author Comment

by:paulp75
ID: 13572650
MySQL said:


You have an error in your SQL syntax.  Check the manual that corresponds to your MySQL server version for the right syntax to use near 'function authenticate ()
{
     $link = mysql_connect('local
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13572656
>> near 'function authenticate () {     $link = mysql_connect('local

.... ?

Where are you calling this funciton ? Did you notice/understand the diffference b/w your function and what I gave you?
0
 
LVL 6

Author Comment

by:paulp75
ID: 13572669
thats after i put it into phpmyadmin.
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13572673
What did you put in phpmyadmin ?

You have to give the MySql query, not the PHP function !
0
 
LVL 6

Author Comment

by:paulp75
ID: 13572708
ok sorry, i've never understood how to work the phpmyadmin
put it in then,
and it found the result
but the script still wont recognise it.
is it because the password is passed with ***'s
its confusing me a fair bit
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13572738
>> is it because the password is passed with ***'s

where do you have the passwords as ***'s ? Do you mean the ***'s in mysql_connect ? If yes, you cannot even connect to the database itself.

please understand that we are not sitting nearby you so we can help all along. We need more details like where this function is being called, do you get any Sql errors, etc.. etc.. What I can tell now without more information is print something related to the query (say the number of rows found using mysql_num_rows($results) ) and see what you get.
0
 
LVL 6

Author Comment

by:paulp75
ID: 13572815
no i mean when you type in the password it puts in
*****
instead of what your typing.


sorry i am trying to give you as much info as i can.
i do appreciate your help a lot.
i thought it may have been from the undefined function error, but was wrong.
it seems like it just isnt accepting the u/p when it runs it through the script as type=password.
even though its in the database.


ok i just changed the script a little so that in the form it wasn't   type=password in the form
and changed the query to
$handle = mysql_query("SELECT * FROM `authenticate_users` WHERE `username` = '" . $_POST['username'] . "' AND `password` =
          '" . $_POST['password'] . "' ") or die("Sql error: " . mysql_error());

taking the MD5 part out for the password.

the query worked great.

but how do i pass it to the query and make it work, if the password is passed in the form as type=password.
ie it is shown on the screen as ****

sorry i wasnt so clear before.
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 13572844
Ah ok, its not a problem but a must to have the type="password" for the password fields. No problem with that.

If you have MD5 encrypted password in the database, you cannot query without converting the user entered password to MD5. I changed the function like this ( for debugging only, you can remove the echo statements later) :

// checks the username and password in the database mentioned below
function authenticate ()
{
     $link = mysql_connect('***','***','***') or die (mysql_error());    // Enter your DB details here :)
     mysql_select_db('***') or die (mysql_error());// Enter your database name :)

     if (trim($_POST['username']) != "") {
          $handle = mysql_query("SELECT * FROM `authenticate_users` WHERE `username` = '" . $_POST['username'] . "' AND `password` = MD5('" . $_POST['password'] . "')") or die("Sql error: " . mysql_error());
         echo mysql_num_rows($handle) . " number of Rows found <br><br>";
          if(mysql_num_rows($handle) < 1) {
               # authentication failed, dont add a cookie, redisplay login with a message
               echo "Sorry. Authentication failed!";
               showlogin ();
          }
          else {
               # authentication was successful, add a cookie and then refresh!
               session_register('username');
               $_SESSION['username'] = $_POST['username'];
               echo "Authentication success!";
               // Uncomment the following line after debugging. //
               // echo "<script language=JavaScript>document.location=\"" . $_SERVER["PHP_SELF"] . "\";</script>";
          }
     }
     else {
       echo "No user name entered!";
     }
}


// Please tell me what output you get for this function. (note the comments I wrote inside the function). One more thing is, where do you call this function ? //
0
 
LVL 6

Author Comment

by:paulp75
ID: 13572884
0 number of Rows found

Sorry. Authentication failed!

with that one.
i'm calling this function from any page on the site.
so if the user hasn't been authenticated then they can't access any page.
but then if they've logged in off another page then they wont keep getting login forms.

ok i think that its the way i've put it into the database for some reason.
because i havent encrypted it at all when putting it into the database.
do you think that'd be the problem?
0
 
LVL 32

Accepted Solution

by:
ldbkutty earned 2000 total points
ID: 13572995
>>  0 number of Rows found

This obviously states that password is the problem. If you have encrypted the password with MD5, you have to use MD5 in the query also. But you have stated that you didnt encrypted the password. So there is no need to apply MD5 in the query.

Echo the query in the function and see if it is the same as what you have entered in the phpmyadmin. Printing the query would clear your problem.
0
 
LVL 6

Author Comment

by:paulp75
ID: 13573089
thanks so much for your help.
i got it working great now

it was the way that i was inputting into the database with the u/p's
sorry about the confusion of what was wrong.
learnt a lot about authentications etc tonight.
thanks heaps
:)
0

Featured Post

Are You Using the Best Web Development Editor?

The worlds of web hosting and web development are constantly evolving. Every year we see design trends change, coding standards adapt and new frameworks/CMS created. With such a quick pace of change it’s easy to get lost trying to keep up.

See if your editor made the list.

Question has a verified solution.

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

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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…
Suggested Courses

762 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