Jump to content

Login issues


Tassadar

Recommended Posts

I am trying to get a login to work for my site and I am almost there.. something about the order or something is throwing it off. So when I type in my username and password I get the "Wrong Username or Password", and Yes I typed the password and username exactly correct. 

<?php

ob_start();
$host="localhost"; // Host name
$username="username"; // Mysql username     <-------edited these for posting purposes
$password="password"; // Mysql password
$db_name="dbname"; // Database name
$tbl_name="tablename"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Define $myusername and $mypassword
$myusername=$_POST['username'];
$mypassword=$_POST['password'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "main.php"
session_register("myusername");
session_register("mypassword");
header("location:main.php");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>

any help is much appreciated!

Link to comment
Share on other sites

  • Replies 50
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Posted Images

is it the first time you're connecting to that database (i.e. with a newly created user in mysql?)... I'm guessing either you didn't set the user's permissions correctly, or something like that. (set permissions fot where the user is allowed to connect from, what databases the user is allowed to see, what actions the user is allowed on each database). If you're using Mamp or Wamp, sometimes a restart to the mysql database gives it a little nudge (it doesn't always commit the permissions properly)

You shouldn't use stripslashes on the $_POSTed password, some people use symbols that will be stripped away.

Always hash your passwords before storing in database (check out md5() or similar hashing functions)

Edited by WebStyles
Link to comment
Share on other sites

this was just a sample login script I found and plugged my login info into.. the one I had before this was even worse. and yeah I use md5 for my passwords. I am able to register and it connects to the DB just fine, but when I login it always tells me my username/password is wrong

Link to comment
Share on other sites

if you're absolutely sure you're using the correct username and password, i'm guessing you have more than one instance of your user and password in the database so the $count variable is greater than 1.

add 'limit 1' to your query, and test again.

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword' limit 1";
Link to comment
Share on other sites

Here is the one I was using before this "sample code" and it didnt seem to work either.. but I think this one is better structured than the sample one:

<?php
session_start();
include("functions.php");
$myConnection = connect();

if(isset($_POST['login'])){
    if(isset($_SESSION['uid'])){
    echo "You are already logged in!";
}else{
    $username = ($_POST['username']);
    $password = ($_POST['password']);
    
    $login_check = mysqli_query($myConnection,"SELECT `id` FROM `user` WHERE `username`='$username' AND `password`='".md5($password)."'") or die(mysql_error());
    if(mysqli_num_rows($login_check) == 0){
        echo "Invalid Username and/or Password combination!";
    }else{
        $get_id = mysqli_fetch_assoc($login_check);
        $_SESSION['uid'] = $get_id['id'];
        $url = 'main.php';
    		echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
    }
}
}else{
    echo "";
}
?>

and function.php is where it connects to the DB:

<?php
$myConnection = connect();

function connect() {
    return mysqli_connect("localhost","xxxxxxxx","xxxxxxxxx","xxxxxxxx");
}

function output($string) {
    echo "<div id=\"output\">" . $string . "</div>";
}

?>

so somewhere between the two, I should be able to get it working.. use the .md5 and I noticed the first one is 

"SELECT * FROM $tbl_name WHERE username='$myusername'

and the second:

"SELECT `id` FROM `user` WHERE `username`='$username'

should I be using SELECT * FROM  or just SELECT `id` FROM ? <----- I think this also is where I might be getting screwed up because every table has a column for ID and Username.. or it may not have anything to do with it.. ;)

Edited by Tassadar
Link to comment
Share on other sites

okay I think its working now.. kinda.

 

on my main page (it only displays if logged in, if not it redirects back to the index so you CAN log in) it just re-directs me to the index.. something in the main page isn't detecting my session?

<?php session_start();
if(!isset($_SESSION['uid'])){
    $url = '/Template/index.html';
    		echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
}else{
    include("safe.php");
    include("functions.php");
?>

(HTML Stuff here)

}
<?php }

Function.php

<?php
$myConnection = connect();

function connect() {
    return mysqli_connect("localhost","xxxxxxxx","xxxxxxxxx","xxxxxxxx");
}

function output($string) {
    echo "<div id=\"output\">" . $string . "</div>";
}

?>

safe.php (which just gathers info from the db for use)

<?php

$stats_get = mysql_query("SELECT * FROM `stats` WHERE `id`='".$_SESSION['uid']."'") or die(mysql_error());
$stats = mysql_fetch_assoc($stats_get);

$unit_get = mysql_query("SELECT * FROM `unit` WHERE `id`='".$_SESSION['uid']."'") or die(mysql_error());
$unit = mysql_fetch_assoc($unit_get);

$user_get = mysql_query("SELECT * FROM `user` WHERE `id`='".$_SESSION['uid']."'") or die(mysql_error());
$user = mysql_fetch_assoc($user_get);

$user_get = mysql_query("SELECT * FROM `structure` WHERE `id`='".$_SESSION['uid']."'") or die(mysql_error());
$user = mysql_fetch_assoc($user_get);


?>
Link to comment
Share on other sites

it's possible that your session_start() is failing and given that you are using a META Refresh to redirect, very likely.

 

when learning php (or anything new in php), or developing or debugging php code, you need to have php's error_reporting set to E_ALL and display_errors set to ON so that php will help you by reporting all the errors it detects.

 

you should set these in your php.ini so that even parse errors in your main file are reported and so that you don't need to remember to put the settings in for development and remove them when putting code onto a live server. you can put the settings into your main file, but they won't help with parse errors in that file and they must go before all your other php statements so that errors that are occurring in any of your other php statements will be reported.

 

btw - you cannot mix both mysql (no i) and mysqli statements on the same database connection. you must pick one set of functions and stick to it throughout all your code and since the mysql (no i) functions are depreciated, you should use only the mysqli functions so that you don't need to rewrite your code in the near future when the mysql (no i) functions are removed.

Edited by mac_gyver
Link to comment
Share on other sites

what would be your current login and main files?

 

btw - i edited my post above while you were writing a reply. when you get to the point of the main.php including the safe.php code, it won't work because of the mix of mysql and mysqli functions and you also still have a mysql_error() statement in your login code that won't work should a query error occur.

Link to comment
Share on other sites

I changed everything to mysqli, added the 2nd parameters required by mysqli and fixed the mysql_error(). Everything works now but still re-directs back to the index as if I wasnt logged in.

 

checklogin.php

<?php
error_reporting(E_ALL);
include("functions.php");
ob_start();
$host="########"; // Host name 
$username="########"; // Mysql username 
$password="########"; // Mysql password 
$db_name="########"; // Database name 
$tbl_name="########"; // Table name 

// Connect to server and select databse.
mysqli_connect("$host", "$username", "$password")or die(mysqli_error($myConnection));
mysqli_select_db($myConnection,"$db_name")or die(mysqli_error($myConnection));

// Define $myusername and $mypassword 
$myusername=$_POST['username']; 
$mypassword=$_POST['password']; 

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysqli_real_escape_string($myConnection,$myusername);
$mypassword = mysqli_real_escape_string($myConnection,$mypassword);
$sql="SELECT `id` FROM `user` WHERE `username`='$myusername' AND `password`='".md5($mypassword)."' limit 1";
$result=mysqli_query($myConnection,$sql);

// Mysql_num_row is counting table row
$count=mysqli_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "main.php"
header("location:main.php");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>

safe.php

<?php

$stats_get = mysql_query($myConnection,"SELECT * FROM `stats` WHERE `id`='".$_SESSION['uid']."'") or die(mysqli_error($myConnection));
$stats = mysql_fetch_assoc($stats_get);

$unit_get = mysql_query($myConnection,"SELECT * FROM `unit` WHERE `id`='".$_SESSION['uid']."'") or die(mysqli_error($myConnection));
$unit = mysql_fetch_assoc($unit_get);

$user_get = mysql_query($myConnection,"SELECT * FROM `user` WHERE `id`='".$_SESSION['uid']."'") or die(mysqli_error($myConnection));
$user = mysql_fetch_assoc($user_get);

$user_get = mysql_query($myConnection,"SELECT * FROM `structure` WHERE `id`='".$_SESSION['uid']."'") or die(mysqli_error($myConnection));
$user = mysqli_fetch_assoc($myConnection,$user_get);


?>

do you need to see my index (where the login form is?)

 

main.php (what should display if logged in)

<?php 
error_reporting(E_ALL);
session_start();
include("functions.php");
if(!isset($_SESSION['uid'])){
    $url = '/Template/index.html';
    		echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
}else{
    include("safe.php");
    
?>

<html>
<meta charset="utf-8">
<title>Aurora</title>
<link href="../style.css" rel="stylesheet" type="text/css">
</head>

<body>
<div style="position: relative" id="wrapper">
  <!-- Menu Panel End -->
  <div id="mainheader">

</div>
  <?php include("statbar.php"); ?>
<div id="sidebar">
  <h3>Navigation</h3>
<?php include("ingamenav.php");?>
<h3>Account</h3>
  <div id="login" class="login"><center><form action="checklogin.php" method="post">
    Username:<br> <input name="username" type="text" class="tb1" maxlength="24"><br />
    Password:<br> <input class ="tb1" type="password" name="password"/><br />
    <input class="tb1" type="submit" name="login" value="Login"/>
    </form></center>
  <p><a href="#">Forgot Password</a><br>
  <a href="#">Register</a><br></p>
   </div>
  
<h3></h3>
<div class="banners">
Reserved for banners
</div>
  
</div>

<div id="content_area">
  <h1>Command Center<span></span></h1>
 <p>The Command Center gives you get a detailed inventory of your resources, military, and the status of your outpost's population.</p>
<div style="position: relative">
<table id="stattable" width="600">
  <tr>
    <th BGCOLOR="#660000" colspan="2" scope="row">Resources</th>
  </tr>
  <tr>
    <th scope="row">Credits</th>
    <th scope="row"><?php echo $user['credits']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Networth</th>
    <th scope="row"><?php echo $user['networth']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Turns</th>
    <th scope="row"><?php echo $user['turns']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Energy</th>
    <th scope="row"><?php echo $user['energy']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Biozene Gas</th>
    <th scope="row"><?php echo $user['gas']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Ore</th>
    <th scope="row"><?php echo $user['ore']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Food</th>
    <th scope="row"><?php echo $user['food']; ?>#</th>
  </tr>
  <tr>
    <th width="294" scope="row">Land</th>
    <th width="294" scope="row"><?php echo $user['land']; ?>#</th>
  </tr>
  <tr>
    <th BGCOLOR="#660000" colspan="2" scope="row">Your Populous</th>
  </tr>
  <tr>
    <th scope="row">Population</th>
    <th scope="row"><?php echo $user['population']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Loyalty</th>
    <th scope="row"><?php echo $user['loyalty']; ?>#</th>
  </tr>
  <tr>
    <th BGCOLOR="#660000" colspan="2" scope="row">Your Military</th>
  </tr>
  <tr>
    <th scope="row">Trainees</th>
    <th scope="row"><?php echo $user['population']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Prisoners of War</th>
    <th scope="row"><?php echo $user['prisoner']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Juggernauts</th>
    <th scope="row"><?php echo $user['juggernaut']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Infantry</th>
    <th scope="row"><?php echo $user['infantry']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Marauders</th>
    <th scope="row"><?php echo $user['marauder']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Recon Squads</th>
    <th scope="row"><?php echo $user['reconsq']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Terminator</th>
    <th scope="row"><?php echo $user['terminator']; ?>#</th>
  </tr>
  <tr>
    <th scope="row">Destroyers</th>
    <th scope="row"><?php echo $user['destroyer']; ?>#</th>
  </tr>
  </table>
</div>
<!--Table of Contents End -->

</div><!--Content Area End -->

<div id="footer">
<p>All Rights Reserved © 2014 <a href="#">Aurora Game</a></p>
</div><!--Footer End -->

</div><!-- Wrapper End -->
</body>
</html>
}
<?php }
Edited by Tassadar
Link to comment
Share on other sites

where and how is $_SESSION['uid'] being set?

good question. I followed a tutorial a while back (which worked for me then) and it used that so I stuck with it. nothing comes up as undefined though.. hmm

 

perhaps using:

$get_id = mysqli_fetch_assoc($myConnection,$login_check);
        $_SESSION['uid'] = $get_id['id'];
        header("Location: main.php");

or something to this extent?

Edited by Tassadar
Link to comment
Share on other sites

well that was a flop and just made things messier. I need to figure out how to define my session key.. whether it be $_SESSION['user'] or $_SESSION['uid'] or whatever.. how exactly do I set this? I think my whole problem is that my sessions are screwed up on my pages

Link to comment
Share on other sites

you need to set both settings that i mentioned. they do different things that together cause errors to be reported and displayed. you are also going to need to remove the output buffering statements from your code and forget you ever saw any ob_start/ob_end_... statements unless you are intentionally trying to buffer output.

 

add - ini_set("display_errors", "1"); to your code.

 

and, another btw - you should not be trying to learn php, develop php, or debug php code on a live web hosting server. it wastes a huge amount of time constantly uploading code (and making sure you actually uploaded the correct code and that the upload worked) just to see the result of each change.

Link to comment
Share on other sites

There seems to be a lot of confusion here, and this is very hard for us to figure out because we have no idea if you're doing the things we're telling you....

Why are you still including 'functions.php' (that had a database connection) if you've got another database connection right after that include?
Why do you still have stripslashes() on your posted password? (that's not the issue, but it's not a good idea.. a password like HX<123>Xt would be destroyed)

Why is ob_start() still there?

 

All this  probably means that the code we're looking at is not the code you're working on right now... It's gonna be very hard to figure this one out if we don't know what's going on.

I suggest you read through the entire post again, apply/try everything we mentioned, then post the final code here again with a detailed explanation of what's still going wrong.

Link to comment
Share on other sites

There seems to be a lot of confusion here, and this is very hard for us to figure out because we have no idea if you're doing the things we're telling you....

Why are you still including 'functions.php' (that had a database connection) if you've got another database connection right after that include?

Why do you still have stripslashes() on your posted password? (that's not the issue, but it's not a good idea.. a password like HX<123>Xt would be destroyed)

Why is ob_start() still there?

 

All this  probably means that the code we're looking at is not the code you're working on right now... It's gonna be very hard to figure this one out if we don't know what's going on.

 

I suggest you read through the entire post again, apply/try everything we mentioned, then post the final code here again with a detailed explanation of what's still going wrong.

Okay lets start fresh so we are on the same page

 

Here is what I have:

 

checklogin.php (file that is ran when user enters their UN and PW and submits form):

<?php
error_reporting(E_ALL);
include("functions.php"); //connection to DB is defined in functions.php

// Define $myusername and $mypassword 
$myusername=$_POST['username']; 
$mypassword=$_POST['password']; 

$myusername = mysqli_real_escape_string($myConnection,$myusername);
$mypassword = mysqli_real_escape_string($myConnection,$mypassword);
$sql="SELECT `id` FROM `user` WHERE `username`='$myusername' AND `password`='".md5($mypassword)."' limit 1";
$result=mysqli_query($myConnection,$sql);

// Mysql_num_row is counting table row
$count=mysqli_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Redirect to file "main.php" if correctly logged in
header("location:/main.php");
}
else {
echo "Wrong Username or Password";
}

?>

Function.php (which contains connection to DB):

<?php
error_reporting(E_ALL);
$myConnection = connect();

function connect() {
    return mysqli_connect("######","######","######","######");
}

function output($string) {
    echo "<div id=\"output\">" . $string . "</div>";
}

?>
  • new php.ini file has been initialized with error reporting set to ON
  • removed stripslashes (ill have to get some kind of protection once I get this working)
  • OB start/end has been removed

It runs everything but still redirects back to Index page rather than moving onto main.php

 

It has something to do with the main.php form it loads when you log in:

<?php 
error_reporting(E_ALL);
session_start();
include("functions.php");
if(!isset($_SESSION['uid'])){
    $url = '/Template/index.html';
    		echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
}else{
    include("safe.php");
    
?>

should I be using if(!isset($_SESSION['id'])){ instead?

Edited by Tassadar
Link to comment
Share on other sites

I changed you're checklogin.php file to this: (read the comments I added)

<?php
error_reporting(E_ALL);
session_start(); // <-- without this you can't set $_SESSION['uid']
include("functions.php"); //connection to DB is defined in functions.php
// Grab & Clean $_POST['username'] and $_POST['password'] :: you should check if they exist first
$myusername = mysqli_real_escape_string($myConnection,trim($_POST['username']));
$mypassword = md5(mysqli_real_escape_string($myConnection,trim($_POST['password'])));
$sql="SELECT `id` FROM `user` WHERE `username` = '$myusername' AND `password` = '$mypassword' limit 1";
$r = mysqli_query($myConnection,$sql);
$result = mysqli_fetch_assoc($r); // <-- Added this to grab the results
// if the query returned a result, set $_SESSION['uid'] and redirect to main.php
if(!empty($result)){ // <-- replaced your count with this: if it's not empty, it means the query returned something
    $_SESSION['uid'] = $result['id'];
    header("location:/main.php");
}else{
    echo "Wrong Username or Password";
}
?>

There are other things you should be doing though... Like check if $_POST['username'] and $_POST['password'] exist and are not empty before trying to manipulate them. personally, I would wrap the whole login file into a function (which would be included in functions.php), and avoid the extra page jump.

Edited by WebStyles
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.