Hi all,

I have just put together a simple log in script from various tutorials on the web and at the moment it is only checking the username entered by the user against what is in my database.
I cant find any infromation about any kind of AND function or any other check the password as well as the username so thats what i need help with

here is what i have already:

<?php
// Connects to your Database
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());;

$uname = $_POST['uname'];
$pword = $_POST['pword'];
//gets username and password from uname and pword fields on previous page

$result = mysql_query("SELECT * FROM logins WHERE uname='$uname'");

if($row = mysql_fetch_array($result))
  {
  setcookie("loggedin", "$uname", time()+3600);
  echo "logged in as: ";
  echo $row['uname'];
  echo "<br />and cookie written.";
  echo "<br />";
  echo 'click <a href="cookie.php">here</a> to view cookie information.<br/><a href="login.php">Back to login page.</a>';
  }
else
{
echo "wrong login information";
}
?>

Thanks guyyys :D

Max

Dani AI

Generated

The original script by sets a cookie after matching only the username. and suggested adding the password check in the query, which fixes the immediate logic hole but still leaves two big problems: SQL injection (never interpolate raw input into SQL) and storing/compared plain-text passwords. For session-based access, a single DB check at login followed by server-side session state is the right approach; for long-lived logins (the "remember me" case asked about) use a secure token scheme, not a raw cookie with credentials.

A minimal, modern login flow:

  • Store only hashed passwords (bcrypt/argon2 via password_hash) in the DB.
  • Authenticate with a prepared statement, then password_verify.
  • On success, call session_start() and session_regenerate_id(true), then store the user id in $_SESSION.

Example (PDO + password_verify):

$stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE username = :u');
$stmt->execute([':u' => $username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user && password_verify($inputPassword, $user['password_hash'])) {
    session_start();
    session_regenerate_id(true);
    $_SESSION['user_id'] = $user['id'];
}

For persistent "remember me" logins, use a selector/validator token pair: store the selector and a hashed validator in the database, set a cookie with the raw selector:validator, and on return locate the selector, hash the validator, and compare with hash_equals. Rotate tokens after use and enforce expiry.

Token generation example:

$selector = bin2hex(random_bytes(9));
$validator = bin2hex(random_bytes(33));
$hash = hash('sha256', $validator);
$expires = time() + 30*24*60*60;

$pdo->prepare('INSERT INTO auth_tokens (user_id, selector, token_hash, expires) VALUES (?, ?, ?, ?)')
    ->execute([$userId, $selector, $hash, date('Y-m-d H:i:s', $expires)]);

setcookie('remember', $selector . ':' . $validator, [
  'expires' => $expires,
  'path' => '/',
  'secure' => true,
  'httponly' => true,
  'samesite' => 'Lax'
]);

Checklist: use HTTPS, HttpOnly/Secure/SameSite cookies, prepared statements (PDO/MySQLi), password hashing (password_hash/password_verify), session ID regeneration, rate-limiting and account lockout on repeated failures, and migrate any plain-text passwords by re-hashing at next login. See the PHP docs for password_hash/password_verify and PDO, and OWASP's Authentication and Session Management guidance for more details (password_hash, password_verify, PDO, OWASP Authentication Cheat Sheet).

Recommended Answers

All 10 Replies

make sure sanatize your inputs to protect against sql injection.

as for the login, just change your query to:

SELECT * FROM logins WHERE uname='$uname' AND password='$pword'

also, a better way to do a login script is to see the number of results returned from the query.

ex.

//run query here
if (mysql_num_rows($result) == 1) {
  //then log the person in
}
else {
  //they have invalid credentials
}

you can change your query like this to validate a username with its password.

(let us say pword is your password table in db...)

replace this:

$result = mysql_query("SELECT * FROM logins WHERE uname='$uname'");

with something like this:

$result = mysql_query("SELECT * FROM logins WHERE uname='$uname' and pword='$pword'");

Ahh! keith is faster than me;) :D

ha xD Thanks guys :) i swear i tried that :P

oh wells thanks for the help guys. and ill def. include the protection against mysql injection

now just to find out what it actually is..... :P

Thanks again.

May I ask related question in here?
I was just reading around, found this thread and remembered that I always wanted to know if it's possible to query database only once, at first visit, to confirm login/pwd is correct.

Basicaly, is there a way to let user browse protected area without checking the database on every page view? (saving id in cookies is not a way :) )

yes, use sessions.

Well, yes, sessions, but is there way to save user identification for long time? (except session in database/files/cookies)

Maybe some new clever way? I know the ordinary one's.

Well, yes, sessions, but is there way to save user identification for long time? (except session in database/files/cookies)

Maybe some new clever way? I know the ordinary one's.

I don't think so..

Well, yes, sessions, but is there way to save user identification for long time? (except session in database/files/cookies)

Maybe some new clever way? I know the ordinary one's.

Try to store the ipaddress of the user and date into a new table then have a timeline for how many days/months etc. on how the id will be saved in that ipadd by subtracting current date from the stored date login...Just my idea...

Yes I do have one. Please pm to get the bulk coupon.
Anybody interested in buying itechbids v7.0 @ 10% discount? Please use
my reseller coupon: RES3215.

I wonder why the mods haven't banned you yet.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.