I have a log in script that currently stores 2 variables a valid variable and a username variable. I am now trying to add in a name variable so I have altered the MySQL query to get the name from the database and have tried to store the name in a session variable but for some reason its just not storing it. Probably best just to show you the script, I have been studying PHP for only 2 months so I really appreciate your help.
<?php
ob_start(); // Start output buffering
session_start(); //must call session_start before using any $_SESSION variables3
$_SESSION['username'] = $username;
function validateUser($username)
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
$_SESSION['name'] = $userData['name'];
}
$username = isset($_POST['username'])?$_POST['username']:'';
$password = isset($_POST['password'])?$_POST['password']:'';
//connect to the database here
$hostname_Takeaway = "localhost";
$database_Takeaway = "diningtime";
$username_Takeaway = "root";
$password_Takeaway = "root";
$Takeaway = mysql_pconnect($hostname_Takeaway, $username_Takeaway, $password_Takeaway) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_Takeaway, $Takeaway);
$username = mysql_real_escape_string($username);
$query = "SELECT name, password, salt FROM admin_users WHERE username = '$username';";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result) < 1) //no such user exists
{
header('Location: http://localhost/diningtime/admin-home.php?login=fail');
die();
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password
{
header('Location: http://localhost/diningtime/admin-home.php?login=fail');
die();
}
else
{
validateUser($username); //sets the session data for this user
}
//redirect to another page or display "login success" message
header('Location: http://localhost/diningtime/main');
die();
//redirect to another page or display "login success" message
?>
Your validateUser() function does not have a $userData variable in scope, so you're assigning NULL to $_SESSION['name'].
Either make $userData be a global so it becomes visible in the function's scope, or pass it as an argument:
function validateUser($user, $userData) {
^^^^^^^^^-- pass as arg
global $userData;
^^^^^^^^^^^^^^^^^--- bring var in-scope
...
$_SESSION['name'] = $GLOBALS['userData']['name'];
^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- refer to global scope
}
Any one of these 3 options would solve the problem (just don't do all three at the same time)
Your validateUser function doesn't get values from $userData array, you need to have another agument in it, like
function validateUser($username, $name)
and then pass those values from your code, or you could move the mysql authentication inside this function and then it will work. Generally, a function doesn't recognize any variable which you define outside of that function.
P.S. What should the fifth line
$_SESSION['username'] = $username;
do? I'm suspecting it from being utterly useless in that place :-)
Lots of mistakes here.
<?php
ob_start(); // Start output buffering
session_start(); //must call session_start before using any $_SESSION variables3
$_SESSION['username'] = $username;
from where $username came?
$username = isset($_POST['username'])?$_POST['username']:'';
$password = isset($_POST['password'])?$_POST['password']:'';
Now you are checking for its existance.
$Takeaway = mysql_pconnect($hostname_Takeaway, $username_Takeaway, $password_Takeaway) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_Takeaway, $Takeaway);
mysql_* deprecation process has started. not related to your problem but worth to mention
then comes validateUser($username); //sets the session data for this user
Now you are calling the function. Let's take a look into the function.
function validateUser($username)
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
$_SESSION['name'] = $userData['name'];
}
You passed $username as parameter but from where $userData['name'] will come? (For scope, refer to MarcBs solution)
So yuu have lot to figure out.
Related
I do a lot of work using PHP frameworks but I am now building a simple login system from scratch and I am stumped. I am using PDO for my database queries. I have a simple login form which points to the same page using $_SERVER['PHP_SELF']. Then I have this code...
<?php
//LOG IN
if($_POST['login_submit']){
$username = $_POST['username'];
$password = $_POST['password'];
//Query
$database->query("SELECT * FROM users WHERE username = :username AND password = :password");
$database->bind(':username',$username);
$database->bind(':password',$password);
$rows = $database->resultset();
$count = count($rows);
if($count > 0){
session_start();
//Assign session variables
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['logged_in'] = 1;
} else {
$login_msg[] = 'Sorry, that login does not work';
}
}
When I login, its fine. It starts the session. But as soon as I go to another page the session is broken. I suspect maybe cause the session_start() is in the if($_POST['login_submit']) condition. But I could sware Ive done it like this before. Any help would be awesome..thanks!
The first line of your code...
if($_POST['login_submit']){
Only, if you submit your login form, the session is started.
And, on all other pages, you have to call session_start() ...
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.
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'";
if(isset($_POST["username"])&& isset($_POST["password"])){
include('config.php'); //this one connects to the database
$username = $_POST["username"];
$password = md5($_POST["password"]);
$sql2=mysql_query("SELECT * FROM clinic_staff WHERE username='$username' AND password='$password'");
$count2 = mysql_num_rows($sql2);
if($count2 == 1){
while($row2 = mysql_fetch_array($sql2)){
$id = $row2["staff_ID"];
$position = $row2["position"];
}
$_SESSION["id"] = $id;
$_SESSION["name"] = $username;
$_SESSION["password"] = $password;
$_SESSION["pos"] = $position;
header("location:index.php");
exit();
}
The problem is I can't echo the username in index.php. I don't know if it is passed successfully. in index.php i used echo $_SESSION["name"];
put session_start(); at the beginning of your document with no white space above it.
You need to look at session_start to start a session. Examples are here
I don't see session_start();. You have to call that function at the top of every page you use session variables. (At least I have to do that on my server, somebody said to me you should actually be able to use Session variables without session_start();, but everything that needed a session variable stopped working after I removed the calls to session_start();)
I'm using this:
function authUser($username, $password){
connectDB();
$sql = "SELECT id, username FROM users where username = '".$username."' and password = '".$password."'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0){
while ($row = mysql_fetch_array($result)){
$username = $row['username'];
session_start();
session_register('username');
return $username;
}
}
closeConn();
}
With a combination of this:
$auth = authUser($username, $password);
if (isset($username)){
header( "Location: index.php" );
}
And then on the index.php (where i redirect them if a successful login) i'm trying to echo $username. But nothing is showing? Any ideas? Is this function the problem?
EDIT:
have now changed it so:
if ($num_rows > 0){
while ($row = mysql_fetch_array($result)){
$_SESSION['username'] = $row['username'];
return true;
}
}
Is that right?
I would change:
while ($row = mysql_fetch_array($result)){
$_SESSION['username'] = $row['username'];
return true;
}
into:
$row = mysql_fetch_array($result);
$_SESSION['username'] = $row['username'];
because you want to login and get ONE person out
Please note that you are always re-directing to index.php, not only on a successful login;
$auth = authUser($username, $password);
if (isset($username)){
header( "Location: index.php" );
}
$username is set, both on a successful and a non-successful login.
You need to use session_start() on the index page as well.
Make sure index.php has a session_start() called at the top of the script, and also, try using $_SESSION['username'] instead of just $username. A lot of servers nowadays are set up so you have to call the full variable (with $_SESSION) rather than just the shortened version. Read about Register Globals at http://php.net/manual/en/security.globals.php. If you still have problems, take the session_start() out of the authUser function and move it to the first line of that script as well.
Variables are not global between page instances, you need to put the variable in $_SESSION if you want it to be accessible over multiple pages.
First, session_register is deprecated. use $_SESSION:
$_SESSION['username'] = $row['username'];
Second, your authUser() function returns either a username (if successful) or nothing. Then this code:
$auth = authUser($username, $password);
if (isset($username))...
should be changed to
$username = authUser($username, $password);
if (isset($username))...
And one more thing, checking for passwords in the clear is a very very bad thing :) Consider hashing it with MD5().
Good luck!
If you use mysql_fetch_array then you should use array, like this: $row[0]
You can use mysql_fetch_assoc() to use table column name ($row['username'])