?
Solved

Why isn't my login system working?

Posted on 2008-06-09
7
Medium Priority
?
226 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
[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
  • 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
Technology Partners: 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 19

Accepted Solution

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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL several years ago, it seemed like now was a good time to update it for object-oriented PHP.  This article does that, replacing as much as possible the pr…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
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…
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