How to access specific mySQL data rows and columns after logging in? - php

This script below is what I'm using to check to see if the user name and password is in my database. This is fine, what I want is now to stay within the row that username and password is found in. In the same row under different columns is more information about the user. I would like to display some of this information in various divs. Not all of it. Examples of the columns other than Password and Email would be "FirstName" and "LastName"
There is also an "Id" column it would be great to be able to do something like "you are logged in, you are Id 10101 and then display FirstName and LastName from current Id.
<?
session_start();
//then do rest of the stuffs//
?>
<?php
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Email: <input type="text" name="Email" /><br />
Password: <input type="password" name="Password" /><br />
<input type="submit" name="submit" value="Login" />
</form>
<?php
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$sql = "SELECT * from stores_db WHERE Email = '{$Email}' AND Password = '{$Password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1)
{
echo "<p>Invalid Email or Password combination</p>";
}
else
{
$recordset = mysqli_fetch_array($result);
$temp_firstname=$recordset['FirstName'];
$temp_lasttname=$recordset['LastName'];
$temp_id=$recordset['Id'];
$_SESSION['user_id']=$temp_id;
header("location:homepage.php"); // direct to your page to show
}
}
?>
Code on homepage.php
<?php
session_start(); echo $_SESSION['user_id']; //to display the id of the logged in user
?>

$sql = "SELECT * from stores_db WHERE Email LIKE '{$Email}' AND Password LIKE '{$Password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1)
{
echo "<p>Invalid username/password combination</p>";
}
else
{
echo "<p>Logged in successfully</p>";
$recordset = mysqli_fetch_array($result);
$temp_firstname=$recordset['FirstName'];
// storing firstname on a variable
$temp_lasttname=$recordset['LastName'];
$temp_id=$recordset['id'];
$_SESSION['user_id']=$temp_id;
header("location:homepage.php"); // direct to your page to show
}
After Doing this,
write
session_start();
echo $_SESSION['user_id']; //to diplay the id of the logged in user
in the page to be foolowed

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
<?
session_start();//at the top most
//then do rest of the stuffs//
?>

<?
session_start();
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Email: <input type="text" name="Email" /><br />
Password: <input type="password" name="Password" /><br />
<input type="submit" name="submit" value="Login" onclick="" />
</form>
<?php
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error} </p>";
exit();
}
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$sql = "SELECT * from stores_db WHERE Email = '{$Email}' AND Password = '{$Password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1)
{
echo "<p>Invalid Email or Password combination</p>";
}
else
{
$recordset = mysqli_fetch_array($result);
$temp_firstname=$recordset['FirstName'];
$temp_lasttname=$recordset['LastName'];
$temp_id=$recordset['Id'];
$_SESSION['user_id']=$temp_id;
$_SESSION['lastname']=$temp_lasttname;
$_SESSION['firstname']=$temp_firstname;
header("location:homepage.php"); // direct to your page to show
}
}
?>
Code on homepage.php
<?php
session_start(); echo $_SESSION['user_id']; //to display the id of the logged in user
?>

Related

Prevent login if a user is already online

When I log in, I'm redirected to a page from my online status, past the preset time, I automatically get back offline. I wanted to change this script so that when I'm online, if someone tries to access my data, she is denied access and redirected to another page, such as google. How can I make these small changes? Thank you.
This is login page
<?php
require_once("functions.php");
require_once("db-const.php");
session_start();
if (logged_in() == true) {
redirect_to("profile.php");
}
?>
<html>
<head>
<title>User Login Form </title>
</head>
<body>
<h1>User Login Form </h1>
<hr />
<!-- The HTML login form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
Remember me: <input type="checkbox" name="remember" /><br />
<input type="submit" name="submit" value="Login" />
Forgot Password?
Register
</form>
<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// processing remember me option and setting cookie with long expiry date
if (isset($_POST['remember'])) {
session_set_cookie_params('604800'); //one week (value in seconds)
session_regenerate_id(true);
}
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if ($result->num_rows != 1) {
echo "<p><b>Error:</b> Invalid username/password combination</p>";
} else {
// Authenticated, set session variables
$user = $result->fetch_array();
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
// update status to online
$timestamp = time();
$sql = "UPDATE users SET status={$timestamp} WHERE id={$_SESSION['user_id']}";
$result = $mysqli->query($sql);
redirect_to("profile.php?id={$_SESSION['user_id']}");
// do stuffs
}
}
if(isset($_GET['msg'])) {
echo "<p style='color:red;'>".$_GET['msg']."</p>";
}
?>
<hr />
</body>
</html>
This is profile page
<?php
require_once("functions.php");
require_once("db-const.php");
session_start();
if (logged_in() == false) {
redirect_to("login.php");
} else {
?>
<html>
<head>
<title>User Profile </title>
<script src="script.js" type="text/javascript"></script><!-- put it on user area pages -->
</head>
<body>
<h1>User Profile </h1>
<hr />
<?php
if (isset($_GET['id']) && $_GET['id'] != "") {
$id = $_GET['id'];
} else {
$id = $_SESSION['user_id'];
}
## connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
## query database
# fetch data from mysql database
$sql = "SELECT * FROM users WHERE id = {$id} LIMIT 1";
if ($result = $mysqli->query($sql)) {
$user = $result->fetch_array();
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
if ($result->num_rows == 1) {
# calculating online status
if (time() - $user['status'] <= (300)) { // 300 seconds = 5 minutes timeout
$status = "Online";
} else {
$status = "Offline";
}
# echo the user profile data
echo "<p>User ID: {$user['id']}</p>";
echo "<p>Username: {$user['username']}</p>";
echo "<p>Status: {$status}</p>";
} else { // 0 = invalid user id
echo "<p><b>Error:</b> Invalid user ID.</p>";
}
}
// showing the login & register or logout link
if (logged_in() == true) {
echo 'Log Out';
} else {
echo 'Login | Register';
}
?>
<hr />
</body>
</html>

How to direct different users to different pages after login?

I created a database (following an online tutorial) which directs all users to one login page. I was wondering how can I direct different users to different webpages. For example I want to direct JOHN SMITH (user1) to localhost/pages/johnsmith.html and JANE SMITH (user 2) to localhost/pages/janesmith.html.
Code:
db_const.php
<?php
# mysql db constants DB_HOST, DB_USER, DB_PASS, DB_NAME
const DB_HOST = 'localhost';
const DB_USER = 'root';
const DB_PASS = 'root';
const DB_NAME = 'ClientDashboard';
?>
login.php
<html>
<head>
<title>User Login Form - PHP MySQL Ligin System | W3Epic.com</title>
</head>
<body>
<h1>User Login Form - PHP MySQL Ligin System | W3Epic.com</h1>
<?php
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" name="submit" value="Login" />
</form>
<?php
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
echo "<p>Logged in successfully</p>";
// do stuffs
}
}
?>
</body>
</html>
register.php
<html>
<head>
<title>User registration form- PHP MySQL Ligin System | W3Epic.com</title>
</head>
<body>
<h1>User registration form- PHP MySQL Ligin System | W3Epic.com</h1>
<?php
require_once("db_const.php");
if (!isset($_POST['submit'])) {
?> <!-- The HTML registration form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
First name: <input type="text" name="first_name" /><br />
Last name: <input type="text" name="last_name" /><br />
Email: <input type="type" name="email" /><br />
<input type="submit" name="submit" value="Register" />
</form>
<?php
} else {
## connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli- >connect_error}</p>";
exit();
}
## query database
# prepare data for insertion
$username = $_POST['username'];
$password = $_POST['password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
# check if username and email exist else insert
$exists = 0;
$result = $mysqli->query("SELECT username from users WHERE username = '{$username}' LIMIT 1");
if ($result->num_rows == 1) {
$exists = 1;
$result = $mysqli->query("SELECT email from users WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) $exists = 2;
} else {
$result = $mysqli->query("SELECT email from users WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) $exists = 3;
}
if ($exists == 1) echo "<p>Username already exists!</p>";
else if ($exists == 2) echo "<p>Username and Email already exists! </p>";
else if ($exists == 3) echo "<p>Email already exists!</p>";
else {
# insert data into mysql database
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `first_name`, `last_name`, `email`)
VALUES (NULL, '{$username}', '{$password}', '{$first_name}', '{$last_name}', '{$email}')";
if ($mysqli->query($sql)) {
//echo "New Record has id ".$mysqli->insert_id;
echo "<p>Registred successfully!</p>";
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error} </p>";
exit();
}
}
}
?>
</body>
</html>
Thanks!
There are some security concerns in your query but just to answer the part you are actually asking, you can add header("Location:" . $url) will redirect to any page.
//if (!$result->num_rows == 1) {
if($result->num_rows !==1){
echo "<p>Invalid username/password combination</p>";
} else {
echo "<p>Logged in successfully</p>";
// do stuffs
header('Location:/' . $result->firstname. $result->lastname. '.html');
}
The most common approach here is to have some generic user page, let's say user.php, that receives as $_GET parameter the id of the user. Then, when a user registers, you redirect him to user.php?id=1, where 1 would be the id of the registered user.
using a switch statment would work with a header
switch ($userName) {
case "JOHN SMITH":
header('location: localhost/pages/johnsmith.html');
break;
case "JANE SMITH":
header('location: localhost/pages/janesmith.html');
break;
default:
header('location: /noname.html');
}
This is ok if you have a very few users, but if you have a lot you would want to store that user's page url and then redirect to it on a successful login
if(USERLOGEDIN){
header('location: ' . $userHomePage);
}
The solution sort of depends, if you are only going to have a few specified users on there, you would only have to put an if statement which redirects to the specified page in login.php, something like:
if (username == 'Whatever the username might be') {
Header("Location: file.html");
} elseif (username == 'Some other user') {
Header("Location: file2.html");
} //so on
This would be after authenticating the password and username though, of course.
I hope this helped, I'm not sure what the solution might be if you're going for something bigger.
(If you get an error saying a header is already existing, use this:
ob_start();
right after <?php above the <html> tag, sometimes you might get an error if you use too many Header functions, ob start should solve this.)
it's not entirely clear from the code where it is directed to after a correct user/pass combo is submitted.
it looks like this is the only part that does anything after verification:
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
echo "<p>Logged in successfully</p>";
// do stuffs
}
if so, try changing it to the below code. note that this solution is required JavaScript as you have already sent headers and so a meta refresh isn't possible.
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
while ($row = $result->fetch_assoc()) {
echo "<p>Logged in successfully</p>";
// do stuffs
echo '<script type="text/javascript">';
echo 'window.location = "http://localhost/pages/.' .$row['first_name']. $row['last_name']. '.htm";';
echo '</script>';
}
}
also note, my code is finding the page name by pulling the first and last names from the db and merging them. You can use a more manual approach if you want but this way you don't need to edit this code to add additional users.

php - redirect user on login

After trying to setup a simple login system with php and MySQL, I was informed of the MySQL depreciation so I started looking into mysqli.
Im still new to PHP and connecting to databases so I found a few online tutorials and I was able to setup a simple login script that works (I used this tutorial http://w3epic.com/php-mysql-login-system-a-super-simple-tutorial/). There is one part I am lost on.
Here is the code from my login page:
<html>
<head>
<title>User Login Form - PHP MySQL Ligin System | W3Epic.com</title>
</head>
<body>
<h1>User Login Form - PHP MySQL Ligin System | W3Epic.com</h1>
<?php
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" name="submit" value="Login" />
</form>
<?php
} else {
require_once("db-const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from clients WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
echo "<p>Logged in successfully</p>";
// do stuffs
}
}
?>
</body>
</html>
It works and I am able to login.
However, I would like to re-direct the user to another page based on if it finds a match in the database or not
My thought was to do something like:
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
header( 'Location: http://www.galactek.com/support/offmaint.html' );
} else {
echo "<p>Logged in successfully</p>";
// do stuffs
header("Location:output.php");
}
However, this produces an error:
Warning: Cannot modify header information - headers already sent by (output started at /home4/galactek/public_html/test/login.php:7) in /home4/galactek/public_html/test/login.php on line 38
How can I successfully redirect the user?
You need to do your password check at the very top of the page. You are not allowed to change the header if anything is written to the output already (like the HTML and head tags before your PHP). Additionally, look up parameterized SQL queries as that will help prevent SQL injections that you are currently vulnerble too
<?php
header("Location: " . my_url);
<?php
$failed = false;
if (isset($_POST["username"]) && isset($_POST["password"])) {
require_once("db-const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from clients WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if ($result->num_rows == 1) {
//redirect the user to their account page since they logged in!
header("Location: http://example.com/youraccount");
} else {
$failed = true;
}
}
?>
<html>
<head>
<title>User Login Form - PHP MySQL Ligin System | W3Epic.com</title>
</head>
<body>
<h1>User Login Form - PHP MySQL Ligin System | W3Epic.com</h1>
<!-- The HTML login form -->
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" name="submit" value="Login" />
</form>
<?php
if ($failed) {
echo "<p>Invalid username/password combination</p>";
}
?>

Trying to create login page using PHP and SQL

I've been working on a website login, and so far, I have the database and register page set up, but I'm trying to work on a Login page. I've been trying to retrieve data from the Database's Table. I was successfull at doing so on my register page to make sure there aren't multiple usernames of the same name, so I copied some of the code and pasted it onto this page. The problem: it returns blank. Please help... ._.
`
KHS SiteSpace
<div id="header">
<img src="./IMAGES/khslogo2.png" style="margin-left:4;float:left;" width="100" hieght="100">
<b>KHS<span id="name">SiteSpace</span></a>
<!--img src="./IMAGES/Menu.png" style="float:right;margin-right:6;" height="100" width="90"-->
</div>
<div id="content">
<p id="subTitle">Login</p>
<div style="float:left;height:30%;">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" id="register"><br>
Username:<br>
<input type="text" name="name"><br><br>
Password:<br>
<input type="password" name="pass">
<br><br>
<input type="submit" value="Confirm">
</form>
</div>
<div style="float:right;width:50%;border-style:none none none solid; border-color:222222;border-width:4;height:30%;">
<p style="margin-left:20;font-size:20;">Output:</p>
<p style="margin-left:20;padding-bottom:15;">
<?php
error_reporting(0);
#ini_set('display_errors', 0);
session_start();
$conn = new mysqli("localhost", "shanedrgn", "getting321", "Users");
if (!$conn) {die("Failure to connect");}
$name = trim($_POST['name']);
$pass = trim($_POST['pass']);
if (empty($name) or empty($pass)) {echo "Empty Fields";} else {
$name = trim($_POST['name']);
$pass = trim($_POST['pass']);
echo "Check: The fields arent empty...";#OUTPUT
echo "Testing Variables...";#OUTPUT
//Error Trapping
$sql = "SELECT Username FROM Users where Username = '$name'";
$Data = mysqli_query($conn, $sql);
if($record=mysqli_fetch_array($Data)) {
$nameTrap = $record['Username'];
}
$sql = "SELECT Address FROM Users where Address = '$address'";
$Data = mysqli_query($conn, $sql);
if($record=mysqli_fetch_array($Data)) {
$ipTrap = $record['Address'];
}
if ($nameTrap == $name) {
echo "Check: Username Exists...";
if ($passTrap == $pass) {
echo "Password is correct!";
$_SESSION['User'] = $name;
$sql = "SELECT * FROM Users where Username = '$name'";
$Data = mysqli_query($conn, $sql);
$record=mysqli_fetch_array($Data);
session_start();
$_SESSION['id'] = $record['id'];
echo "<script>alert('You have successfully logged in!')</script>";
sleep(4);
header("Location: ./index.php"); /* Redirect browser */
exit();
} else { echo "Password Invalid";}
} else {echo "That username doesn't exist!";echo $name.";;";echo $nameTrap;}
}
?>
</p></div>
</div>
</body>
</html>`
EDIT: Added missing code
You are doing this:
echo "<script>alert('You have successfully logged in!')</script>";
sleep(4);
header("Location: ./index.php"); /* Redirect browser */
I understand, what you try, but it can't work. You can't set an Header after sending Body-Content - what you do using echo.
You should use JavaScript for your redirect, after the 4 second timeout. Use setTimeout and window.location.

PHP Login Form - Not Seeing mySQL Rows

Simple Question: Trying to create a php login form. My database is connected successfully. I currently have 1 table row in mySQL. So why is my $numrow variable echoing 0/ Why is my username in my database not being recognized? What am I missing? Please, help. Not a php expert.
Thanks!
<?php
include 'includes/top.php';
?>
<?php
error_reporting(0);
session_start();
$connect = mysql_connect("localhost", "hostname", "password") or die ("Couldn't connect!");
mysql_select_db("djones33") or die ("Couldn't find db!");
$query = mysql_query("SELECT * FROM tm_user WHERE username='$username'");
$numrows = mysql_num_rows($query);
echo $numrows;
if ($numrows!=0) {
while ($row = mysql_fetch_assoc($query)) {
$db_username = $row['username'];
$db_password = $row['password'];
}}
if (isset($_POST["username"])) {
$username = $_POST["username"];
//they did, so now, has the username AND password been entered?
if ((isset($_POST["username"])) && (isset($_POST["password"]))){
//they have, now, is the username correct?
if ($_POST["username"]!=$db_username && $_POST["username"]!=""){
$uerror="<p class='error'>* The username you entered is not correct.</p>";
//echo "$uerror";
} else {
echo "";
}
//now, is the password correct?
if ($_POST["password"]!=$db_password && $_POST["password"]!=""){
$perror="<p class='error'>* The password you entered is not correct.";
//echo "$perror";
} else {
echo "";
}
//they haven't entered a username, so...
if ($_POST["username"]=="") {
$emptyu="<p class='error'>* You must enter a username.</p>";
//echo $emptyu;
}
//they haven't entered a username, so...
if ($_POST["password"]=="") {
$emptyp="<p class='error'>* You must enter a password.</p>";
//echo $emptyu;
}
//if the username and password are correct, give them the welcome page!
if ($_POST["username"]==$db_username && $_POST["password"]==$db_password) {
echo "";
$_SESSION['username']=$db_username;
//$welcome = "Welcome, ".$user. "! You have successfully logged in.";
}
}
}
?>
<h2><span class="green_title">Welcome</span><br><span class="title_size">to YOUR.to-do!</span></h2>
<section id="login_area">
<div id="login_title">
<p>Login</p>
</div>
<div id="form_area">
<form action="login.php" method="post">
<?php echo $uerror; echo $emptyu;?>
<input type="text" name="username" placeholder="username" id="username"/><br/>
<?php echo $perror; echo $emptyp;?>
<input type="password" name="password" placeholder="password" id="password"/><br/>
<input type="submit" name="submit" value="LOGIN" class="button"/>
</form>
</div>
</section>
<footer>
<p>New user? | Register</p>
</footer>
</div>
</div>
</body>
</html>
Have a look at PHP's built-in Password Hashing Functions and the PDOStatement Class. When your users register be sure to use password_hash() on the passwords they submit before saving them in your database. And when you query your database use PDOStatements and bound parameters to keep your site safe from SQL injection attacks.
Your log in script should look something like this:
$db = new PDO('mysql:host=localhost;dbname=Database_Name', 'Username', 'Password');
$ps = $db->prepare("SELECT * FROM tm_user WHERE username = (:username)");
$ps->bindParam(":username", $_POST["username"]);
$ps->execute();
$result = $ps->fetch(); // $result is an array representing the row in tm_user with the submitted username
if(count($result) === 0)
{
// username not found
}
else if(password_verify($_POST["password"], $result["password"]) === false)
{
// password is incorrect
}
else if(password_verify($_POST["password"], $result["password"]) === true)
{
// give them the welcome page!
}
Remember: password_verify() will only work if you used password_hash() on the password before storing it in the database.

Categories