Solved

Why isn't my login system working?

Posted on 2008-06-09
7
219 Views
Last Modified: 2013-12-13
For whatever reason, i can't get my login system to work.  i figure it has something to do with cookies or whatnot. yes i know that this code leaves me open to injection attacks & my password isn't hashed, but this is just for testing it at the moment (and i've got no idea how to protect against injections)

in any case, this is my code

if(isset($_COOKIE['ID_my_site']))
{
      if ('ID_my_site')
      //if there is, it logs you in and directes you to the members page
      {
            $username = $_COOKIE['ID_my_site'];
            $pass = $_COOKIE['Key_my_site'];
            
            $check = mysql_query("SELECT * FROM users WHERE username = '$username'");
                        
            while($info = mysql_fetch_array( $check ))
            {
                  if ($pass != $info['password'])
                  {
                        echo("wrong password");
                  }
            }
      }
}
//IF FORM HAS BEEN SUBMITTED
if (isset($_POST['submit']))
{
      if(!$_POST['username'] | !$_POST['pass'])
      {
            //die('You did not fill in a required field.');
      }

      $check = mysql_query("SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());

      $check2 = mysql_num_rows($check);
      if ($check2 == 0)
      {
            die('check2 is zero!!!<a href=index.php><br> Try again</a>');
      }

      while($info = mysql_fetch_array( $check ))
      {
            $_POST['pass'] = stripslashes($_POST['pass']);
            $info['password'] = stripslashes($info['password']);            
            $_POST['pass'] = ($_POST['pass']);
            
            //gives error if the password is wrong
            if ($_POST['pass'] != $info['password'])
            {
                  //die('Incorrect password, please try again.');
                  die('password wrong 2!!!<a href=index.php><br>Try again</a>');
            }
      
            else
            {
                  // if login is ok then we add a cookie
                  ob_start();
                  $username = stripslashes($_POST['username']);
                  $pass = stripslashes($_POST['pass']);
                  $hour = time() + 3600;
                  setcookie('ID_my_site', $username, $hour,"/db/","www.prospect-select.com",false);
                  setcookie('Key_my_site', $pass, $hour,"/db/","www.prospect-select.com",false);
                  header("Location: index.php");
                  ob_end_flush();                  
      }
            

      }
}
//IF USER HASN'T SUBMITTED FORM
else
{
      //just displays a login form, which when submitted runs through the checking at the top of the code snippet
}

this is the login check placed on every page

ob_start();
include ("config.php");

if(isset($_COOKIE['ID_my_site']))
{
      $username = $_COOKIE['ID_my_site'];
      $pass = $_COOKIE['Key_my_site'];
      $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());
      while($info = mysql_fetch_array( $check ))
      {
            if ($pass != $info['password'])
            {
                  header("Location: login.php");
            }
      }
}

else
{
      header("Location: login.php");
}

ob_end_clean();

problem here is that i'll login using a valid password, and it won't log me in, i'm 99% sure theres a problem setting cookies

thanks in advance
0
Comment
Question by:Abyssmal
  • 3
  • 2
7 Comments
 
LVL 19

Expert Comment

by:BrianGEFF719
ID: 21748252
In order to authenticate a user you need to use Session Cookies, not Persistent Cookies. Read about session cookies here, this will allow you to save information on the server side that's tied to that user's session:

     http://us.php.net/manual/en/ref.session.php

You would do something like this:

 session_start(); /* always start the session before you do anything */

 if($authenticated)
 {
   $_SESSION['username'] = $username;
 }
 

Now on another page you would check if that's set, if not you will redirect to login page:

 session_start();
 if(isset($_SESSION['username']))
 {
   echo "Hey There {$_SESSION['username']}\n";
 }
 else
 { /* force user to login to see this page */
   header('Location: http://www.mysite.com/login.php');
 }

To logout you would make a page called logout.php:

 session_start();
 session_destroy();
 /* session was killed, send back to login page */
 header('Location: http://www.mysite.com/login.php');






Now, you always need to make sure your inputs are filtered to avoid SQL Injection, php has built in functions to help you do this:
 
  http://us.php.net/manual/en/function.mysql-real-escape-string.php
  http://us.php.net/manual/en/function.mysql-escape-string.php

Example usage:

 $query = "SELECT * FROM users WHERE username = '" . mysql_real_escape_string($username) . "'";
 $check = mysql_query($query)or die(mysql_error());
 
0
 
LVL 11

Expert Comment

by:AlexanderR
ID: 21748288
BrianGEFF719
Thats the best option but what he has should work fine.  He has username and password stored in cookies and they are compared to the ones in database on top of every page.  Logic is fine, just need to find the error in code.

Abyssmal:

I am trying to recreate the scenario on my computer but i don't follow how you have your file names set up.  This code i guess is from page login.php ?  Then what is the name of the form for login input and last 23 lines show up on top of every page?
0
 

Author Comment

by:Abyssmal
ID: 21748647
well my file names are setup login.php for the first chunk of code, and loginCheck.php is included on every page, as its name says to check whether or not the login cookie is set, if so then they get the content of the page, of not theyre redirected back to the login page
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 19

Accepted Solution

by:
BrianGEFF719 earned 500 total points
ID: 21749020
You have many logical errors in your site, I don't have time to check your code line by line, but here are a few:



>>if ('ID_my_site')

A string will always result as true. I doubt this is the logic you meant to perform.

>>if(!$_POST['username'] | !$_POST['pass'])

A single bar is a BITWISE operation double bar is LOGICAL OR. You need to change it to ||, ie:  if(!$_POST['username'] || !$_POST['pass'])


>>while($info = mysql_fetch_array( $check ))

mysql_fetch_array returns an indexed array, you're treating it as an associative array, in which case you need to use mysql_fetch_assoc()
 eg:  while($info = mysql_fetch_assoc($check))

>>if(!$_POST['username'] | !$_POST['pass'])

Again, double bars for logical OR. Also, I thnk you want to check if they are set, so you would do:

 if(!isset($_POST['username']) || !isset($_POST['pass']))
  echo 'something not set ;/';

>>$_POST['pass'] = ($_POST['pass']);

Umm, what is the purpose of this?




0
 

Author Comment

by:Abyssmal
ID: 21755283
so you think i should just scrap all my code and start fresh?
0
 
LVL 19

Expert Comment

by:BrianGEFF719
ID: 21755707
Yes, and I would avoid using persistent cookies for session data.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Browsers only know CSS so your awesome SASS code needs to be translated into normal CSS. Here I'll try to explain what you should aim for in order to take full advantage of SASS.
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
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 …

914 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

19 Experts available now in Live!

Get 1:1 Help Now