1
<?php
session_start();
error_reporting(E_ALL ^ E_DEPRECATED);
$host = "localhost";
$user = "root";
$pass = "";
$db = "testing";
mysql_connect($host, $user, $pass);
mysql_select_db($db);
if (isset($_POST['loginID'])) {
    $loginID = $_POST['loginID'];
    $password = $_POST['password'];
    $sql = "SELECT * FROM user WHERE loginID='".$loginID."' AND password='".$password."' LIMIT 1";
    $res = mysql_query($sql);
    if (mysql_num_rows($res) == 1) {
        header("Location:homepage.php");
        $_SESSION['loginID'] = $loginID;
    } else {
        header("Location:login.php");die;
    }
}
?>

I want to pass the username in a session, to show the username in homepage.php, but it didn't work when I tried to do so. What is wrong, and how can I make it work?

Léo Lam
  • 3,870
  • 4
  • 34
  • 44
David
  • 23
  • 4
  • 3
    Move this line - $_SESSION['loginID']=$loginID; - before you set your header. – WillardSolutions May 27 '14 at 17:33
  • 3
    Never, ever use unsanitized user input in a query. – GeminiDomino May 27 '14 at 17:34
  • Your code will never got setting Session value line; because you are redirecting to another page by `header("Location:homepage.php");` – Javad May 27 '14 at 17:35
  • Sorry inform that I make some mistake.. what I actually mean is,, I login my web using loginID (example-111111) and password(example-abcde). After login into my homepage. I want to retrieve the username(example-alex) from my database. – David May 27 '14 at 17:39
  • as a suggestion to your code : If you will use the query like you write and not use parametrized query you risk being hacked by sql injection – TotPeRo May 27 '14 at 18:20

3 Answers3

1

Change this:

if(mysql_num_rows($res)==1)
{
header("Location:homepage.php");
$_SESSION['loginID']=$loginID;
}

to this:

if(mysql_num_rows($res)==1)
{
$_SESSION['loginID']=$loginID;
header("Location:homepage.php");
}
WillardSolutions
  • 2,316
  • 4
  • 28
  • 38
0

session value should be stored first and then redirect to another page. Try following: if(mysql_num_rows($res)==1) { $_SESSION['loginID']=$loginID; header("Location:homepage.php"); }

SonaliM
  • 1
  • 1
0

You need to fetch a row from your result set and use information from that row for your session variable:

$res = mysql_query($sql);
if ($row = mysql_fetch_assoc($res)) {
    $_SESSION['loginID'] = $loginID;
    $_SESSION['name'] = $row['username'];    // or whatever the column is called where the username is stored
    header("Location:homepage.php");
    exit();
} else {
    header("Location:login.php");die;
}

Apart from that a few comments:

  • You should switch to PDO or mysqli using prepared statements. The mysql_* functions are deprecated and you have an sql injection problem now;
  • You should never store plain-text (or encrypted...) passwords. Passwords should be salted and hashed, see Secure hash and salt for PHP passwords
Community
  • 1
  • 1
jeroen
  • 91,079
  • 21
  • 114
  • 132