When a user logs into my website a session is created with their "user id". When they want to go change their account information they can click the button and they will be redirected to the "developer_infoupdater.php" file. But every time they change their information, the session ends and they are logged out. I want them to stay logged in after they change their information. I believe the problem is on the "developerUpload.php" file because i am checking if their information is current and if not redirect them to the logout page. And when i changed the destination from logout to a different file, it went to the file that i changed it to. So what I want is for the user to stay logged in after they update their account information. Here is my code
Developer Upload file
<?php
session_start();
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
//Check if TOKEN used to log in, is actually there
$token = $_SESSION['token'];
$stmtToken = $handler->prepare("SELECT * FROM token_table WHERE token = :token");
$stmtToken->execute(array(':token'=>$token));
if($rowToken = !$stmtToken->fetch()){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerSignup.php");
exit;
}
//Check if information is still in there has changed
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$fullname = $_SESSION['fullname'];
$email = $_SESSION['email'];
$password = $_SESSION['password'];
$stmtChecker = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id= :userid AND fullname = :fullname AND username = :username AND email = :email");
$stmtChecker->execute(array(':userid'=>$userid, ':fullname'=>$fullname, ':username'=>$username, ':email'=>$email));
if(!$resultChecker = $stmtChecker->fetch()){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
if(!password_verify($password, $resultChecker['password'])){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
if(isset($_COOKIE['id'])){
if(isset($_POST['changeSettings'])){
$_SESSION['token'] = $token;
$_SESSION['id'] = $userid;
$_SESSION['came_from_upload'] = true;
header("Location: developer_infoupdater.php");
exit;
}
}
info update file
<?php
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['id'])){
if($_SESSION['came_from_upload'] != true){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
error_reporting(E_ALL & ~E_NOTICE);
if($_SERVER['REQUEST_METHOD'] =="POST"){
$token = $_SESSION['token'];
$userid = $_SESSION['id'];
$fullname = addslashes(trim($_POST['fullname']));
$username = addslashes(trim($_POST['username']));
$email = addslashes(trim($_POST['email']));
$password = addslashes(trim($_POST['password']));
$storePassword = password_hash($password, PASSWORD_BCRYPT, array('cost' => 10));
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$stmtChecker = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id = :userid");
$stmtChecker->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmtChecker->execute();
if($result = !$stmtChecker->fetch()){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
if(!empty($fullname)){
$stmtFullname = $handler->prepare("UPDATE generalusersdata SET fullname = :fullname WHERE user_id = :userid");
$stmtFullname->bindParam(':fullname', $fullname, PDO::PARAM_STR);
$stmtFullname->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmtFullname->execute();
}
if(!empty($username)){
$stmtCheckerUsername = $handler->prepare("SELECT * FROM generalusersdata WHERE username = :username");
$stmtCheckerUsername->bindParam(':username', $username, PDO::PARAM_STR);
$stmtCheckerUsername->execute();
if($resultCheckerUsername = $stmtCheckerUsername->fetch()){
die("Username Already in use! Please try again");
}
$stmtUsername = $handler->prepare("UPDATE generalusersdata SET username = :username WHERE user_id = :userid");
$stmtUsername->bindParam(':username', $username, PDO::PARAM_STR);
$stmtUsername->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmtUsername->execute();
}
if(!empty($email)){
if(filter_var($email, FILTER_VALIDATE_EMAIL) == false){
die ("Email is Not Valid!");
}
$stmtCheckerEmail = $handler->prepare("SELECT * FROM generalusersdata WHERE email = :email");
$stmtCheckerEmail->bindParam(':email', $email, PDO::PARAM_STR);
$stmtCheckerEmail->execute();
if($resultCheckerEmail = $stmtCheckerEmail->fetch()){
die("Email Already in use! Please try again");
}
$stmtEmail = $handler->prepare("UPDATE generalusersdata SET email = :email WHERE user_id = :userid");
$stmtEmail->bindParam(':email', $email, PDO::PARAM_STR);
$stmtEmail->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmtEmail->execute();
}
if(!empty($password)){
if(strlen($password) < 6){
die ("Password has to be GREATER than 6 characters!");
}
//Check if password has atleast ONE Uppercase, One Lowercase and a number
if(!preg_match("(^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$)",$password)){
echo 'Password needs to be at least ONE uppercase, ONE lowercase, and a number!';
exit;
}
$stmtPassword = $handler->prepare("UPDATE generalusersdata SET password = :password WHERE user_id = :userid");
$stmtPassword->bindParam(':password', $password, PDO::PARAM_STR);
$stmtPassword->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmtPassword->execute();
}
if($_FILES['file']['error'] == UPLOAD_ERR_OK){
$file_tmp = file_get_contents($_FILES['file']['tmp_name']);
//keep only A-Z and 0-9 and everything else KILL
$file_name = preg_replace("/[^a-z0-9\.]/", "_", strtolower($_FILES['file']['name']));
$file_name = strtotime("now")."_".$file_name;
$mime = mime_content_type($_FILES['file']['tmp_name']);
if(strstr($mime, "video/")){
die("Please note that this file is NOT an image... Please select an image for your Profile Picture");
}else if(strstr($mime, "image/")){
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG);
$detectedType = exif_imagetype($_FILES['file']['tmp_name']);
if($extensionCheck = !in_array($detectedType, $allowedTypes)){
die("Failed to upload image; the format is not supported");
}
$dir = "devFiles/";
$uploadedFile = $dir . basename($_FILES['file']['name']);
if(is_dir($dir)==false){
mkdir($dir, 0700);
}
if(!move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFile)){
die("There was an error moving the file... Please try again later!");
}
$stmtFile = $handler->prepare("UPDATE generalusersdata SET profile_image = :file_name, file_tmp = :file_tmp WHERE user_id = :userid");
$stmtFile->bindParam(':file_name', $file_name, PDO::PARAM_STR);
$stmtFile->bindParam(':file_tmp', $file_tmp, PDO::PARAM_STR);
$stmtFile->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmtFile->execute();
}
}
$_SESSION['id'] = $userid;
$_SESSION['token'] = $token;
header("Location: developerUpload.php");
exit;
}
}else{
header("Location: developerLogin.php");
exit;
}
?>
Indeed when changing your user information it doesn't match what was previously cached in the session ( this is logical ). Seems to me you have 2 choices.
Update session data when making edits ( hard to maintain )
Check only the primary key of the user (this is what i would do)
$userid = $_SESSION['id'];
/* Nuke this stuff
$username = $_SESSION['username'];
$fullname = $_SESSION['fullname'];
$email = $_SESSION['email'];
$password = $_SESSION['password']; // I wouldn't persist the password, what do we need it for after login,
*/
//Look up the user by ID only
$stmtChecker = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id= :userid");
$stmtChecker->execute(array(':userid'=>$userid));
if(!$resultChecker = $stmtChecker->fetch()){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}else{
//if a user with this ID exists update session data.
$_SESSION['username'] = $resultChecker['username'];
$_SESSION['fullname'] = $resultChecker['fullname'];
$_SESSION['email'] = $resultChecker['email'];
}
Related
Every time a user submits a picture for their "profile pic" it will display as a "broken image" and I noticed that when I physically insert an image into the mysql data base and display it, it works perfectly and the size of the file changes to "BLOB - KiB" instead of MB. But when I insert that same image into the database using my "upload file", that image turns to "BLOB MB" and doesn't display on the website. I saw some post about this and they said to remove the "addslashes" from the variable and i did that but it still didn't work. So what i wan't to do is display the image from the database that was submitted by the user. It works when you physically insert it into the database without a file but if you do it with one, it doesn't work. Here is a screen shot of the database structure, upload file, and retrieving file.
PHP Upload file
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post') { //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['username'])) {
if($_SESSION['came_from_upload'] != true) {
setcookie("username", "", time() - 60 * 60);
$_COOKIE['username'] = "";
header("Location: developerLogin.php");
exit;
}
error_reporting(E_ALL & ~E_NOTICE);
if($_SERVER['REQUEST_METHOD'] == "POST") {
$token = $_SESSION['token'];
$userid = $_SESSION['id'];
$fullname = addslashes(trim($_POST['fullname']));
$username = addslashes(trim($_POST['username']));
$email = addslashes(trim($_POST['email']));
$password = addslashes(trim($_POST['password']));
$storePassword = password_hash($password, PASSWORD_BCRYPT, array(
'cost' => 10
));
$file_tmp = addslashes(trim($_FILES['file']['tmp_name']));
$file_name = addslashes(trim($_FILES['file']['name']));
try {
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
die("There was an error connecting to the database");
}
$stmtChecker = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id = ?");
$stmtChecker->execute(array(
$userid
));
if($result = !$stmtChecker->fetch()) {
setcookie("username", "", time() - 60 * 60);
$_COOKIE['username'] = "";
header("Location: developerLogin.php");
exit;
}
if(!empty($fullname)) {
$stmtFullname = $handler->prepare("UPDATE generalusersdata SET fullname = ? WHERE user_id = ?");
$stmtFullname->execute(array(
$fullname,
$userid
));
}
if(!empty($username)) {
$stmtCheckerUsername = $handler->prepare("SELECT * FROM generalusersdata WHERE username = ?");
$stmtCheckerUsername->execute($username);
if($resultCheckerUsername = $stmtCheckerUsername->fetch()) {
die("Username Already in use! Please try again");
}
$stmtUsername = $handler->prepare("UPDATE generalusersdata SET username = ? WHERE user_id = ?");
$stmtUsername->execute(array(
$username,
$userid
));
}
if(!empty($email)) {
if(filter_var($email, FILTER_VALIDATE_EMAIL) == false) {
die("Email is Not Valid!");
}
$stmtCheckerEmail = $handler->prepare("SELECT * FROM generalusersdata WHERE email = ?");
$stmtCheckerEmail->execute($email);
if($resultCheckerEmail = $stmtCheckerEmail->fetch()) {
die("Email Already in use! Please try again");
}
$stmtEmail = $handler->prepare("UPDATE generalusersdata SET email = ? WHERE user_id = ?");
$stmtEmail->execute(array(
$email,
$userid
));
}
if(!empty($password)) {
if(strlen($password) < 6) {
die("Password has to be GREATER than 6 characters!");
}
//Check if password has atleast ONE Uppercase, One Lowercase and a number
if(!preg_match("(^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$)", $password)) {
echo 'Password needs to be at least ONE uppercase, ONE lowercase, and a number!';
exit;
}
$stmtPassword = $handler->prepare("UPDATE generalusersdata SET password = ? WHERE user_id = ?");
$stmtPassword->execute(array(
$storePassword,
$userid
));
}
if($_FILES['file']['error'] == UPLOAD_ERR_OK) {
$mime = mime_content_type($_FILES['file']['tmp_name']);
if(strstr($mime, "video/")) {
die("Please note that this file is NOT an image... Please select an image for your Profile Picture");
} else if(strstr($mime, "image/")) {
$allowedTypes = array(
IMAGETYPE_PNG,
IMAGETYPE_JPEG
);
$detectedType = exif_imagetype($_FILES['file']['tmp_name']);
if($extensionCheck = !in_array($detectedType, $allowedTypes)) {
die("Failed to upload image; the format is not supported");
}
$dir = "devFiles/";
$uploadedFile = $dir . basename($_FILES['file']['name']);
if(is_dir($dir) == false) {
mkdir($dir, 0700);
}
if(!move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFile)) {
die("There was an error moving the file... Please try again later!");
}
$stmtFile = $handler->prepare("UPDATE generalusersdata SET profile_image = ?, file_tmp = ? WHERE user_id = ?");
$stmtFile->execute(array(
$file_name,
$file_tmp,
$userid
));
}
}
$_SESSION['token'] = $token;
header("Location: developerUpload.php");
exit;
}
} else {
header("Location: developerLogin.php");
exit;
}
HTML
<form method="post" enctype="multipart/form-data" autocomplete="off">
Information Changer<br>
Fullname: <input type="text" name="fullname" placeholder="Full Name.....">
<br/>
<br/>
Username: <input type="text" name="username" placeholder="User Name.....">
<br/>
<br/>
Email: <input type="text" name="email" placeholder="Email.....">
<br/>
<br/>
Password: <label><input type="password" name="password" placeholder="Password....." ></label>
<br></br>
Profile Picture: <input type="file" name="file">
<br/>
<input type="submit" name="submit">
</form>
Retrieving file
try {
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
die("There was an error connecting to the database");
}
$stmt = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id = :userid");
$stmt->bindValue(':userid', '61', PDO::PARAM_INT);
$stmt->execute();
while($result = $stmt->fetch()) {
echo '<img src="data:image/jpeg;base64,' . base64_encode($result['file_tmp']) . '"/>';
}
You are storing the temporay filename - not its contents.
$file_tmp = addslashes(trim($_FILES['file']['tmp_name']));
Should be
$file_tmp = file_get_contents($_FILES['file']['tmp_name']);
How to get the value of the column 'ProfilePicture' for the current user (which is stored in a session) from a database and save it into a variable?
Here is an example of a possible structure for the query:
if($email="iahmedwael#gmail.com" show 'ProfilePicture' value for that username) //declare a variable to save the value of ProfilePicture
<?php
$posted = true;
if (isset($_REQUEST['attempt'])) {
$link = mysqli_connect("localhost", "root", "", 'new1') or die('cant connect to database');
$email = mysqli_escape_string($link, $_POST['email']);
$password = mysqli_escape_string($link, $_POST['Password']);
$query = mysqli_query($link, " SELECT *
FROM 360tery
WHERE Email='$email'
OR Username= '$email'
AND Password='$password' "
) or die(mysql_error());
$total = mysqli_num_rows($query);
if ($total > 0) {
session_start();
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
} else {
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
For security purposes, it's my recommendation that you use PDO for all your database connections and queries to prevent SQL Injection.
I have changed your code into PDO. It should also get the value from the column ProfilePicture for the current user and save it to the variable $picture
Note: you will need to enter your database, name and password for the database connection.
Login Page
<?php
session_start();
$posted = true;
if(isset($_POST['attempt'])) {
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$email = $_POST['email'];
$password = $_POST['Password'];
$stmt = $con->prepare("SELECT * FROM 360tery WHERE Email=:email OR Username=:email");
$stmt->bindParam(':email', $email);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
if(password_verify($password, $row['Password'])) {
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
}else{
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
}
?>
User Page
<?php
session_start();
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$stmt = $con->prepare("SELECT ProfilePicture FROM 360tery WHERE username=:email OR Email=:email");
$stmt->bindParam(':email', $_SESSION['email']);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
$picture = $row['ProfilePicture'];
}
?>
Please let me know if you find any errors in the code or it doesn't work as planned.
So I have a simple login script, but when I started encrypting passwords and using password_verify I seem to get the same result all the time, false. Here's my login script
<?php
session_start();
$host = "localhost";
$user = "root";
$pass = "root";
$dbname = "users";
try{
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
$email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
$pass = htmlspecialchars($_POST['password'], ENT_QUOTES, 'UTF-8');
$st = $con->prepare("SELECT * FROM users WHERE email = :email AND password = :pass");
$st->bindValue(':email', $email, PDO::PARAM_STR);
$st->bindValue(':pass', $pass, PDO::PARAM_STR);
$st->execute();
$rows = $st->fetch(PDO::FETCH_NUM);
if($email === ''){
$_SESSION['message1'] = 'Enter a valid email';
header('Location: index.php');
exit();
}
elseif($pass === ''){
$_SESSION['message1'] = 'Enter a valid password';
header('Location: index.php');
exit();
}
elseif($rows > 0){
$_SESSION['loggedin'] = true;
$hash = $con->prepare("SELECT password FROM users WHERE email = :email");
$hash->bindValue(':email', $email);
$hash->execute();
}
elseif(password_verify($pass, $hash)){
$name = $con->prepare("SELECT name FROM users WHERE email = :email");
$name->bindValue(':email', $email, PDO::PARAM_STR);
$name->execute();
$rows = $name->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$_SESSION['name'] = $row['name'];
}
header('Location: profile.php');
}
else{
$_SESSION['message1'] = 'Make sure email and password are correct';
header('Location: index.php');
exit();
}
?>
Also here's how I'm encrypting
$passh = password_hash($pass, PASSWORD_DEFAULT)."\n";
$db = $con->prepare("INSERT INTO users (name, email, password) VALUES (:name, :email, :passh)");
$db->bindValue(':name', $name, PDO::PARAM_STR);
$db->bindValue(':email', $email, PDO::PARAM_STR);
$db->bindValue(':passh', $passh, PDO::PARAM_STR);
$db->execute();
$_SESSION['name'] = $name;
$_SESSION['email'] = $email;
$_SESSION['loggedin'] = true;
header('Location: profile.php');
exit();
Error reporting is enabled, but for some reason its still not working and simply displays Make sure email and password are correct, which come from the next else statement. Any ideas? I'm fairly new. Also any security tips would be great. Thanks in advance.
UPDATED CODE
<?php
session_start();
$host = "localhost";
$user = "root";
$passw = "root";
$dbname = "users";
try{
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $passw);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
$email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
$pass = htmlspecialchars($_POST['password'], ENT_QUOTES, 'UTF-8');
$hash = $con->prepare("SELECT password FROM users WHERE email = :email");
$hash->bindValue(':email', $email);
$hash->execute();
$rows1 = $hash->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows1 as $row1) {
$_SESSION['hash'] = $row1['hash'];
}
$st = $con->prepare("SELECT * FROM users WHERE email = :email AND password = :pass");
$st->bindValue(':email', $email, PDO::PARAM_STR);
$st->bindValue(':pass', $pass, PDO::PARAM_STR);
$st->execute();
$rows = $st->fetch(PDO::FETCH_NUM);
if($email === ''){
$_SESSION['message1'] = 'Enter a valid email';
header('Location: index.php');
exit();
}
elseif($pass === ''){
$_SESSION['message1'] = 'Enter a valid password';
header('Location: index.php');
exit();
}
elseif($rows > 0 || password_verify($pass, $hash) ){
$_SESSION['loggedin'] = true;
$name = $con->prepare("SELECT name FROM users WHERE email = :email");
$name->bindValue(':email', $email, PDO::PARAM_STR);
$name->execute();
$rows = $name->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$_SESSION['name'] = $row['name'];
}
header('Location: profile.php');
}
else{
$_SESSION['message1'] = 'Make sure email and password are correct';
header('Location: index.php');
exit();
}
?>
Look at your query one more time:
SELECT password FROM users WHERE email = :email
You are selecting the column password,
when you fetch the row you are using the field hash
$_SESSION['hash'] = $row1['hash'];
Unlike you think, your script is not simple at all, you are performing 3 queries on the same record, try this approach
$email = $_POST['email'];
$pass = $_POST['password'];
if($email === ''){
$_SESSION['message1'] = 'Enter a valid email';
header('Location: index.php');
exit();
}
if($pass === ''){
$_SESSION['message1'] = 'Enter a valid password';
header('Location: index.php');
exit();
}
$query = 'SELECT name, email, password
FROM users
WHERE email = :email LIMIT 1';
$stmt = $con->prepare($query);
$stmt->bindValue(':email', $email);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$row){
$_SESSION['message1'] = 'User does not exist';
header('Location: index.php');
exit();
}
//hashed password from Database
$hash = $row['password'];
if(password_verify($pass, $hash)){
$_SESSION['hash'] = $row['password'];
$_SESSION['name'] = $row['name'];
$_SESSION['email'] = $row['email'];
header('Location: profile.php');
}else{
$_SESSION['message1'] = 'Make sure email and password are correct';
header('Location: index.php');
exit();
}
So my SELECT statement is selecting all from a row in the users table. There is a column in that row labeled "user_level" and I want to use the data from that column to differentiate between an admin and a guest. Is there a way to use "user_level" (and maybe bind it to a session variable) without me having to write another SELECT statement?
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare("SELECT * FROM users WHERE user_name = :name and
user_password = :password");
$query->bindValue(":name", $username, PDO::PARAM_STR);
$query->bindValue(":password", $password, PDO::PARAM_STR);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
//user entered correct details
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
//user entered false details
$error = 'Incorrect details!';
}
}
}
You don't need no rowCount here.
as well as half of the duplicated and triplicated code.
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql = "SELECT user_level FROM users WHERE user_name = ? and user_password = ?";
$stm = $pdo->prepare($sql);
$srm->execute(array($username,$password));
$level = $stm->fetchColumn();
if ($level !== FALSE) {
//user entered correct details
$_SESSION['user_level'] = $level;
header('Location: index.php');
exit();
}
}
$error = 'Incorrect details!';
I've written a functional login script using MySQL. However, I've now been told that it needs to be done using PDO, and I've a functional PDO connection:
function getConnection()
{
$userName = '*****';
$password = '*****';
$dbname = '******';
$db = new PDO("mysql:host=localhost;dbname=$dbname", $userName, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
However I've no idea how to convert the login query to PDO.
if (isset($_REQUEST['attempt']))
{
$user = $_POST['user'];
$password = $_POST['password'];
$qry = mysql_query
("SELECT *
FROM subscriber
WHERE email = '$user'
AND password = '$password'")
or die(mysql_error());
$total = mysql_num_rows($qry);
if ($total > 0)
{
session_start();
$_SESSION['user'] = 'yes';
header('location: account.php');
exit;
}
else
{
// Do nothing.
}
}
How can I do it?
To get you started:
$db = getConnection();
$stmt = $db->prepare("
SELECT * FROM subscriber WHERE email = :email AND password = :password
");
$stmt->bindParam(":email" , $user );
$stmt->bindParam(":password", $password);
$stmt->execute();
$total = $stmt->rowCount();
Non-bloated version:
$stm = $pdo->prepare("SELECT * FROM subscriber WHERE email = ? AND password = ?");
$stm-> execute($_POST['user'], $_POST['password']);
if ($id = $stm->fetchColumn()) {
session_start();
$_SESSION['user'] = $id;
header('location: account.php');
exit;
}
You can also use this example if you would not like to use bindParam. But I extracted it from #eggyal's answer. Great thanks go to eggyal.
<?php session_start();
include_once('pdo.inc.php');
$username = (isset($_POST['username']))? trim($_POST['username']): '';
$password = (isset($_POST['password']))? $_POST['password'] : '';
$pas = md5($password);
$redirect = (isset($_REQUEST['redirect']))? $_REQUEST['redirect'] :
'view.php';
$query = ("SELECT username FROM site_user WHERE username=:username
AND password =:password");
$query_login = $con->prepare($query);
$query_login->execute(array(
':username'=>$username,
':password'=>$pas));
$result = $query_login->rowCount();
if($result>0)
{
$_SESSION['username'] = $username;
$_SESSION['logged'] = 1;
echo "success";
}
else {
// Set these explicitly just to make sure
echo 'User name invalid';
}
?>