Solved

Why isn't my login system working?

Posted on 2008-06-09
7
218 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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

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.
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to dynamically set the form action using jQuery.
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

706 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

16 Experts available now in Live!

Get 1:1 Help Now