-1

Basically I'm having difficulty getting the 'user_id' value from a database and storing it in a session.

What I have:

I have a login page which requests the users username and password. Upon submitting, they are taken to an authentication page. Providing a matching combination is submitted, the user is granted access - If there is not a matching combination, they are redirected away.

In the MySQL database, I have a column for 'user_id', 'username' and 'password'. And my authentication page is:

<?php
require "connect.php"; // connects to db
connection();

session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$user_id=$row['user_id'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['user_id'] = $user_id;


$result= mysql_query("SELECT * FROM users WHERE username='$username' and password='$password' and type='user'");

if(($row = mysql_fetch_array($result)))
{       
print_r($_SESSION);
//header('Location: welcome.php');
}
else
{
header('Location: not-authorized.php');
}
?>

When I print the session, I am displayed with:

Array ( [username] => cm89 [password] => conrad1 [user_id] => ) 

I have tried a number of different ways, and cannot get the users ID to store to the session. The 'user_id' is a numeric value, generated with auto incriminate.

If someone could put me on the right tracks, that would be great. Thanks.

Cœur
  • 34,719
  • 24
  • 185
  • 251
Conrad M
  • 193
  • 1
  • 1
  • 11
  • 2
    Lovely [SQL injection attack](http://bobby-tables.com) vulnerabilities. This is especially **HORRIBLE** since you're storing passwords in-the-clear in the database. What site is this for, so I can blacklist the entire IP subnet? – Marc B Apr 08 '14 at 19:54
  • @MarcB now now - let him get hack his own way - one bird to kill at a time, its now codereview - once he put it over there - then we can rip him apart – azngunit81 Apr 08 '14 at 20:21

1 Answers1

1

$row['user_id'] doesn't exist. You pull it out of thin air. That's why you have no value for $_SESSION['user_id'].

You need to get that value after you query your database. Not before.

<?php
require "connect.php"; // connects to db
connection();

session_start();
$username=$_POST['username'];
$password=$_POST['password'];

$_SESSION['username'] = $username;
$_SESSION['password'] = $password;

$result= mysql_query("SELECT * FROM users WHERE username='$username' and password='$password' and type='user'");

if(mysql_num_rows($result))
{       
    $row = mysql_fetch_array($result);
    $user_id=$row['user_id'];
    $_SESSION['user_id'] = $user_id;
    // Or more concisely
    // $_SESSION['user_id'] = $row['user_id'];
    header('Location: welcome.php');
}
else
{
    header('Location: not-authorized.php');
}
?>

Notes:

Zoe stands with Ukraine
  • 25,310
  • 18
  • 114
  • 149
John Conde
  • 212,985
  • 98
  • 444
  • 485