PHP log in error undefined index - php

I am trying to log in using this code :
session_start();
require "connect.php";
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrow = mysql_num_rows($query);
if($numrow!=0)
{
while($row = mysql_fetch_assoc($query))
{
$db_username = $row['username'];
$db_password = $row['password'];
}
if($username==$db_username&&$password==$db_password)
{
//echo 1;
header("Location: members.php");
$_SESSION['username']=$db_username;
}
else echo 0;
}
else die("That user doesn't exist");
}
else die("Please enter a username and password");
upon successful log in it should take me to members.php :
session_start();
if($_SESSION['username']) <------ this is line 5
{
echo "20730312";
echo " You are logged in as: ".$_SESSION['username'];
echo "<p><a href='logout.php'>Click here to logout</a>";
}
but when i request members.php in my application it gives me :
Notice: Undefined index: username in E:\Program Files\xampp\htdocs\adddrop\members.php on line 5
note that i am using android webview to request members.php after successful log in, is this right ? what am i doing wrong ?

On a side note: you have an SQL injection there. Might want to read more: http://en.wikipedia.org/wiki/SQL_injection
The problem you are facing is that the username is not always POST'd (when you just load the page first time):
$username = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
That should fix it. Basically, I check if the POST index is set, and only if it is I try to access it, otherwise I set it to null.
Also, you might want to do it like this:
$query = mysql_query("SELECT * FROM users WHERE username='" . mysql_real_escape_string($username) . "'");
That prevents the SQL injection vulnerability.
And also add exit;:
header("Location: members.php");
$_SESSION['username']=$db_username;
exit; // Add this.

Same as always. You're not POSTing to the URL. Verify the URL you're attempting to POST to.

perhaps this:
header("Location: members.php");
$_SESSION['username']=$db_username;
should be changed to (reverse):
$_SESSION['username']=$db_username;
header("Location: members.php");

As it says, you don't have the specified data from POST. Make sure your form action is right and you're filling out the username.
Also, you might want to consider hashing your passwords. From what I can see here you compare plain text passwords (or you're already getting hashed passwords to your script, which would be ok).

Related

Php login code, data does not match

Here is my code that I made when I tried to make a login page to my site. I get wrong details everytime I try to login, I have checked the details several times so that they match, I do get a clear dbconnection so there is not a problem with that either. I do not have an md5 encryption so that I have thought of too... I use LONGTEXT as datatype in my mysql database for storage of name and password. I got 3 rows of information in the table users of the database. ID, Name, password, named exactly as I have written.
I hope this was enough information to get some help?
Thanks in advance!
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_SESSION['user'])!=""){
header("Location: index.php");
}
if(isset($_POST['login'])){
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res = mysql_query("SELECT * FROM users WHERE Name='$email'");
$row = mysql_fetch_array($res);
if($row['password']==$upass){
$_SESSION['user'] = $row['user_id'];
header("Location: index.php");
} else {
?>
<script>alert('wrong details');</script>
<?php
}
}
?>
You don't need to do this because will not pass this to the query anyway.
$upass = mysql_real_escape_string($_POST['pass']);
The value of the password is not equal to the value of the escaped password. So this will not be accurate.
if($row['password']==$upass){}
You could just do something like
if($row['password']==$_POST['pass']){}
I would suggest following fixes to your script..
1) Make sure that the name should be unique in your db table..
e.g. if some one has already registered with name as "admin" then do not allow any other person use that as username( or name in your case) to use.
2) Check name and password both in the query it self.
See the below modified code..
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_SESSION['user'])!="")
{
header("Location: index.php");
}
if(isset($_POST['login']))
{
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res = mysql_query("SELECT * FROM users WHERE Name='$email' AND password = '$upass' ");
if($res) // check if there is any error in the query
{
if(mysql_num_rows($res) == 1) // check for the number of Name - password pair
{
$row = mysql_fetch_array($res);
$_SESSION['user'] = $row['user_id'];
header("Location: index.php");
}
else
{
?>
<script>alert('wrong details');</script>
<?php
}
}
else
{
echo "Error while log in: ".mysql_error();
}
}
?>
Note:
1) Stop using mysql_. They are deprecated Use mysqli_ or PDO
2) Make sure that you have used proper columns names in PHP code, similar to those in the db table.

Displaying username using $_SESSION['username']

When I try to display the username of a logged-in user I get 'Welcome, 1' where 1 should be the username of the person logged in.
This is my code in the members.php. The commented out line doesn't work either.
<?php
require_once('include.php');
?>
<?php
// echo "welcome, {$_SESSION['username']}";
$user = $_SESSION['username'];
echo "Welcome $user";
?>
The user is logged in, I wonder if I've made a mistake in the check-login page.
The code for the check_login page is:
<?php
require_once('include.php');
$username = trim($_POST['user']);
$password = trim($_POST['pass']);
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM user WHERE username='$username' and password='$password';";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count !== 0){
$_SESSION['logged-in'] = true;
header("location:members.php?user=$username");
exit;
}
else {
$_SESSION['logged-in'] = false;
header("location:login_again.php");
exit;
}
?>
which redirects to the members.php page upon successful login.
Anybody have any ideas why the username is '1' everytime?
Many thanks
there needs to be a session_start() somewhere at the top of your code
<?php session_start();
require_once('include.php');
?>
<?php
// echo "welcome, {$_SESSION['username']}";
$user = $_SESSION['username'];
echo "Welcome $user";
?>
you also need to set it before accessing it with session_start at the top of this file also
if($count>0){
$_SESSION['username']=$username;
$_SESSION['logged-in'] = true;
header("location:members.php?user=$username");
exit;
}
your code is open for sql injection attacks, Use prepared statements instead
In your check_login page I don't see either session_start and the code for saving username into session so that you can retrieve it on the other page.
In check_login page please add:
session_start();
at the start and then set:
$_SESSION['username'] = $username;
so that you can retrieve and display it on the other page.
Please check following points.
Make sure you set username in the Session variable.
From your code, I do not see any line like following:
$_SESSION['username'] = $username
Without setting, you can get nothing.
If you did session_start() before using $_SESSION variable.
session_start() is required function to be called if you gonna use $_SESSION variable.

PHP: Get username from session

I'm not very good at PHP and I have a little problem. I've been playing around with this script.
And I can't for the life of me figure out how to echo the username of a logged in user.
I tried to print all the information of the session like this:
var_dump($_SESSION)
but I just got the hashed password and the userlevel int.
Can someone maybe help me here? I just want to be able to echo the username.
You have to store the username in the session for it to be available on another page load, currently the script only stores these values in the session;
$_SESSION['loggedin'] = $row[$this->pass_column];
$_SESSION['userlevel'] = $row[$this->user_level];
What you have to do is add the $username to the session that is passed into the login function, like below;
$_SESSION['username'] = $username;
The username will now be stored in the session with the key username.
To be able to use it on another page, make sure that before attempting to use it you initiate the session by calling the function session_start().
Basically, just write it inside like
session_start();
echo $_SESSION['username'];
or
echo $_SESSION['password'];
A brief explanation of how sessions work.
first you start the session and assign any value to a session ex:
session_start();
$_SESSION['username'] = 'john';
then echoing works like:
echo $_SESSION['username']; // will echo out 'jonh'
note session_start() must be shared in-between the pages you want to use the session
You have session_start(); on top ?
In the login function you should write the username to the session after a successful login.
//instantiate if needed
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
if($_REQUEST['action'] == "login"){
if($log->login("logon", $_REQUEST['username'], $_REQUEST['password']) == true){
//do something on successful login
$_SESSION['username'] = $_REQUEST['username'];
}else{
//do something on FAILED login
}
}
<?php
include('db.php');
session_start();
$name=$_POST['name'];
$password=$_POST['password'];
echo $sql="SELECT * FROM register WHERE (name='$name' OR email='$name') AND password='$password'";
$result=mysqli_query($conn,$sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0)
{
$_SESSION['user']=mysqli_fetch_assoc($result);
$row = $_SESSION['user'];
$role = $row['role'];
if($role == 1)
{
header('location:usermanagement.php');
}
else{
header('location:user.php');
}
}
else
{
echo "Wrong Username or Password";
header('location:login.php');
}
$conn->close();
?>

php login authentication failing

I'm relatively new to php, and I'm trying to write a really simple login script. I've got the basic functionality down, but I can't login to the system. My login script is below, and my registration script is below as well.
checklogin.php
include_once 'inc/db.inc.php';
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
try {
$sql="SELECT id, username, password FROM users WHERE username='$username' and password='$password'";
$result = $pdo->query($sql);
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count == 1){
// Register $username, $password and redirect to file "index.php"
session_register("username");
session_register("password");
header("Location: index.php");
}
else {
header("Location: login.php?invalid=1");
}
}
catch (PDOException $e) {
echo $e;
}
ob_end_flush();
?>
checkreg.php
include_once 'inc/db.inc.php';
//This makes sure they did not leave any fields blank
if (!$_POST['username'] | !$_POST['password'] | !$_POST['passwordconf'] ) {
die('You did not complete all of the required fields');
}
if ($_POST['password'] != $_POST['passwordconf']) {
die('Your passwords did not match. ');
}
$_POST['password'] = md5($_POST['password']);
if (!get_magic_quotes_gpc()) {
$_POST['password'] = addslashes($_POST['password']);
$_POST['username'] = addslashes($_POST['username']);
}
$username = $_POST['username'];
$password = $_POST['password'];
try {
// now we insert it into the database
$sql = "INSERT INTO users(username,password) VALUES ('$username','$password')";
$result = $pdo->exec($sql);
header("Location: index.php");
} catch (PDOException $e){
echo $e;
}
?>
I know that the registration is writing to the database, but everytime I attempt a valid login I receive my invalid credentials flag. Anything you can do to help me would be awesome. Thank you.
Your issue could be with session_register(), depending on the version of PHP you're using. Try putting
session_start();
At the top of checklogin.php, then using
...
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
...
instead of session_register().
First you should clear some things out:
1.
if (!$_POST['username'] | !$_POST['password'] | !$_POST['passwordconf'] ) {
die('You did not complete all of the required fields');}
it should be && and not |.
In your code there's nowhere to check if username exists or not, so i'm guessing that you have multiple users with the same username. Before inserting in your checkreg.php, you should fist check if the username exists or not.
in your checklogin.php change if($count == 1) to if($count > 0)
If this not helped could you give me more information like database data (the data that is in your database now)
<?php
// Use of session_register() is deprecated
$barney = "A big purple dinosaur.";
session_register("barney");
// Use of $_SESSION is preferred, as of PHP 4.1.0
$_SESSION["zim"] = "An invader from another planet.";
// The old way was to use $HTTP_SESSION_VARS
$HTTP_SESSION_VARS["spongebob"] = "He's got square pants.";
?>
Warning:
This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
Couple of things to try:
1) The session_register function call is deprecated. http://php.net/manual/en/function.session-register.php. You really ought to be using $_SESSION if at possible.
Something like this:
$_SESSION["username"] = $username;
$_SESSION["password"] = "validated"; // md5 is variable so you can't easily check for it on next page render
2) When testing for the values, you don't want $_POST, you want to use $_SESSION again on the next page render. Something like this:
if ("validated" == $_SESSION["password"]) {
// You're logged in...
}
3) Note, for the $_SESSION array to be populated you must call session_start(); once and only once before use. (http://www.php.net/manual/en/function.session-start.php for more.)
4) I know this is sample code, but SQL Injection attack possible. Need to escape those variables.
$sql="SELECT id, username, password FROM users WHERE username='$username' and password='$password'";

PHP session_start question

So i'm writing a simple login script and I ran into some problems. I was able to create the login.php file that works with this dashboard.php file below. Let me describe the scenario: User come into the main page, which is the login page. Enters username and password. If entered correctly user will see the output "dashboard succesfull". If entered wrongly it will redirect them to loginfailed.php. Problem is that the browser does not remember that the user has already been logged in. If I re-enter this page, it will directly goes to loginfailed.php. So my obivous n00b question here is......is there a way to make the browser remember that the user has already been logged in?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$dblink = mysql_connect("localhost", "root", "");
mysql_select_db("user",$dblink);
$sql = "select * from members where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
$count = 0;
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
echo "<a href='dashboard.php'>dashboard succesfull</a>";
} else {
$_SESSION['loggedIn'] = "false";
header("Location: loginfailed.php");
}
?>
Sure. You just need to put, at the top of the page but below session_start(), something like:
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'true') {
# do something. maybe redirect and then exit?
}
Also, I'd suggest using a session name and escaping the username and password before putting them in your SQL.

Categories