I'm trying to make a page so users can update their username, email, and password. I have made this script, not sure if it should work or not. When I click update it doesn't make any changes to the account. Not sure what it is. I left the HTML stuff out.
<?php
session_start();
require 'core/init.php';
$uname = $_GET['username'];
$username = $_SESSION['username'];
if(isset($_POST['update'])) {
$uname = $_GET['username'];
if(!empty($_POST['username'])) {
$updateuname = $db->prepare("UPDATE users SET username = :username WHERE username='".$uname."'");
$updateuname->bindValue(':username', $_POST['username'], PDO::PARAM_STR);
$updateuname->execute();
if(!empty($_POST['email'])) {
$updateemail = $db->prepare("UPDATE users SET email = :email WHERE username='".$uname."'");
$updateemail->bindValue(':email', $_POST['email'], PDO::PARAM_STR);
$updateemail->execute();
if(!empty($_POST['password'])) {
if(empty($_POST['password_c'])) {
echo 'You must enter your password in both boxes!';
} else {
if($_POST['password'] == $_POST['password_c']) {
$updatepassword = $db->prepare("UPDATE users SET password = :password WHERE username='".$uname."'");
$updatepassword->bindValue(':password', $_POST['password'], PDO::PARAM_STR);
$updatepassword->execute();
} else {
echo 'Passwords did not match';
}
}
}
}
}
echo 'Details updated!';
}
?>
Related
I have been working for 2 days on a login and authentication system in PHP. For my logic it should be perfect, but I have problems as usual.
Here is the code:
<?php
ob_start();
session_start();
include "../navbar.php";
require_once '../database-connection.php';
include "../login.html";
if (isset($_SESSION['session_id'])) {
header('Location: ../index.php');
exit;
}
if (isset($_POST['login'])) {
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
$query = "
SELECT email, password
FROM users
WHERE email = :email
";
$check = $pdo->prepare($query);
$check->bindParam(':email', $email, PDO::PARAM_STR);
$check->execute();
$user = $check->fetch(PDO::FETCH_ASSOC);
if ($email == $user['email']) {
if (password_verify($password, $user['password'])) {
session_regenerate_id();
$_SESSION['session_id'] = session_id();
$sql = "
SELECT username, id FROM users
WHERE email = :email";
$check = $pdo->prepare($sql);
$check->bindParam(':email', $email);
$check->execute();
$user = $check->fetch();
$_SESSION['session_user'] = $user['username'];
$_SESSION['email'] = $email;
$_SESSION['user_id'] = $user['id'];
header('Location: ../index.php');
exit;
} else {
$msg = "Wrong Password";
}
} else {
$msg = "Wrong Email";
}
printf($msg, 'back');
}
The system works, it allows me to authenticate the users registered in the database, but I don't understand why the $msg variable that I use for errors is not printed.
Or better any echo that I put in any part of the listing is not printed.
I can't print anything anywhere. It looks like the program just hangs after the first few includes, yet it lets me authenticate.
(Yes guys I debug by printing the echo to understand up where the scripts work!)
I am trying to display the name of a user when they are logged in. My code uses $_SESSIONS to store the name, but since there no input in my login in page, the name doesn't get assign and it ends up being just hello, instead of something like hello, John Smith.
I've tried using sql to select the name by matching the email to the email of the logged in user, and storing that in $_SESSION but it still doesn't print name of user.
my server.php
<?php
include_once "inc/user-connection.php";
session_start();
$name = mysqli_real_escape_string($conn, $_POST['name']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
if (isset($_POST['admin-sign-in'])) {
if (!empty($email)) {
if (!empty($password)) {
$sql = 'SELECT email, password FROM admin WHERE email = ?';
// preparing the SQL statement
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$stmt->store_result(); // Store the result so we can check if the account exists in the database.
// If email exists in sign_up table
if ($stmt->num_rows > 0) {
$stmt->bind_result($email, $password);
$stmt->fetch();
// if password user enters matches the one in the database
if (password_verify($password, $hashed_password)) {
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$_SESSION['name'] = $row['name'];
// upon successful login, redirect user to landing apge
header("location: dashboard.php");
die();
} else {
// Incorrect password
header("location: ../html/sign-in-error.html");
die();
}
} else {
// Incorrect username
header("location: ../html/sign-in-error.html");
die();
}
$stmt->close();
}
} else {
header("location: ../html/404-error.html");
die();
}
} else {
header("location: ../html/404-error.html");
die();
}
}
my dashboard.php
<?php
session_start();
?>
<div class="d-block">
<h1 class="lead fw-normal text-muted mb-4 px-lg-10">Hello,
<?php
echo $_SESSION['name'];
?>
</h1>
</div>
You did not select the name and you are fetching it.
$sql = 'SELECT email, password, name FROM admin WHERE email = ?';
or
$sql = 'SELECT * FROM admin WHERE email = ?';
should fix the issue.
Additional: you can remove all your else statements since all of it will give the same result.
<?php
include_once "inc/user-connection.php";
session_start();
$name = $_POST['name'];
$password = $_POST['password'];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$email = $_POST['email'];
$username = $_POST['username'];
if (isset($_POST['admin-sign-in'])) {
if (!empty($email)) {
if (!empty($password)) {
$sql = 'SELECT * FROM admin WHERE email = ?';
// preparing the SQL statement
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$stmt->store_result(); // Store the result so we can check if the account exists in the database.
// If email exists in sign_up table
if ($stmt->num_rows > 0) {
$stmt->bind_result($email, $password, $name);
$stmt->fetch();
// if password user enters matches the one in the database
if (password_verify($password, $hashed_password)) {
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$_SESSION['name'] = $row['name'];
// upon successful login, redirect user to landing apge
header("location: dashboard.php");
die();
}
}
$stmt->close();
}
}
}
header("location: ../html/404-error.html");
die();
}
I want to do is when a user click the login button and the inputs are empty its will echo please enter email and password and if the user put email and password wrong it will echo incorrect email and password .
My problem is when i click the login button and the inputs are empty it echo both please enter email and password and incorrect email and password.
I want to echo please enter email and password if both email and password are empty only and if one of email or password is wrong it should echo incorrect email and password.
<?php
require 'encryption.php';
include_once('database.php');
$db = new Connection();
$db = $db->dbConnect();
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$email = $_POST['email'];
$pass = $_POST['password'];
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
$hash = '*';
$login = $db->prepare("SELECT user_password FROM tbl_user WHERE user_email= :email");
$login->bindParam(':email', $email, PDO::PARAM_STR);
$login->execute();
$hash = $login->fetchColumn();
if(empty($email) && empty($pass)){
echo "Please enter Email and Password";
}
if($hasher->CheckPassword($pass, $hash))
{
$st = $db->prepare("SELECT * from tbl_user WHERE user_email=? AND user_password=? AND user_active='1'");
$st->bindParam(1, $email, PDO::PARAM_STR);
$st->bindParam(2, $hash, PDO::PARAM_STR);
$st->execute();
if($st->rowCount() === 1){
echo "1";
exit;
}
}else{
echo "Incorrect Email or Password";
}
?>
Change your second if to elseif.
Basically this:
if(empty($email) && empty($pass)){
echo "Please enter Email and Password";
} else {
if ($hasher->CheckPassword($pass, $hash))
echo "works"
} else {
echo "doesn't work"
}
}
So In my project I'm trying to declare a variable so it will display their full name if logged in. I'm assuming it would be a query to fetch the data from the table but I'm unsure on how to have it make sure it get's that certain user's name and not the first name on the table
Here's my registration code.
if( $user->is_logged_in() ){ header('Location: index.php'); }
//if form has been submitted process it
if(isset($_POST['submit'])){
//very basic validation
if(strlen($_POST['username']) < 3){
$error[] = 'Username is too short.';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $_POST['username']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['username'])){
$error[] = 'Username provided is already in use.';
}
}
if(strlen($_POST['password']) < 3){
$error[] = 'Password is too short.';
}
if(strlen($_POST['passwordConfirm']) < 3){
$error[] = 'Confirm password is too short.';
}
if($_POST['password'] != $_POST['passwordConfirm']){
$error[] = 'Passwords do not match.';
}
//email validation
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$error[] = 'Please enter a valid email address';
} else {
$stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
$stmt->execute(array(':email' => $_POST['email']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$error[] = 'Email provided is already in use.';
}
}
//email validation
if(strlen($_POST['fullname']) < 2){
$error[] = 'Please enter a valid full name';
} else {
$stmt = $db->prepare('SELECT fullname FROM members WHERE fullname = :fullname');
$stmt->execute(array(':fullname' => $_POST['fullname']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$error[] = 'Email provided is already in use.';
}
}
//if no errors have been created carry on
if(!isset($error)){
//hash the password
$hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);
//create the activasion code
$activasion = md5(uniqid(rand(),true));
try {
//insert into database with a prepared statement
$stmt = $db->prepare('INSERT INTO members (username,password,email,fullname,active) VALUES (:username, :password, :email, :fullname, :active)');
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':fullname' => $_POST['fullname'],
':active' => $activasion
));
$id = $db->lastInsertId('memberID');
//send email
$to = $_POST['email'];
$subject = "Registration Confirmation";
$body = "Thank you for registering at demo site.\n\n To activate your account, please click on this link:\n\n ".DIR."activate.php?x=$id&y=$activasion\n\n Regards Site Admin \n\n";
$additionalheaders = "From: <".SITEEMAIL.">\r\n";
$additionalheaders .= "Reply-To: $".SITEEMAIL."";
mail($to, $subject, $body, $additionalheaders);
//redirect to index page
header('Location: index.php?action=joined');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
}
Updated with the user class:
<?php
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT password FROM members WHERE username = :username');
$stmt->execute(array('username' => $username));
$row = $stmt->fetch();
return $row['password'];
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$hashed = $this->get_user_hash($username);
if($this->password_verify($password,$hashed) == 1){
$_SESSION['loggedin'] = true;
return true;
}
}
public function logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
return true;
}
}
}
Why not simply select them from the database?
Please don't mind me if I mix in a little pseudo code since I'm not very familiar with your variables.
First, you create/start a SESSION if the login credentials are correct.
if($login_credentials_correct){ //lol you know what I mean here
session_start();
$_SESSION['username'] = $_POST['username']; // or wherever it may have come from
}
Now that the session is on, you can perform a query somewhat similar to this
<?php
session_start(); // fixed
$username = $_SESSION['username'];
$stmt = $db->prepare('SELECT fullname FROM members where username= :username');
$stmt->execute(array(':username'=>$username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$fullName = $row['fullName']; //I am not sure if this is the correct index.
//to make sure, use var_dump($row) and find out which index has the full name
echo $fullName; //voila.
?>
Now, this code only works if your username is unique. Lol. which site has no unique username.
Can you post your log in code? I'll try to answer with what you ave so far.
If you want users to have the ability to log in and have their data available for display do this
if(!($_SERVER['REQUEST_METHOD'] == "POST")){
//Code here for users trying to access page incorrectly
}else{
if(isset($_POST['username']) && ($_POST['username'] <= $UsernameMaxLength)){
$username=strip_tags(stripslashes($_POST['username'])); //Clean the data up
}else{
//Error handling code
}
if(isset($_POST['password']) && ($_POST['password'] <= $PasswordMaxLength)){
//I would advise you use SHA1() instead for password encryption, but I'll use what you used here
$password=$user->password_hash(strip_tags(stripslashes($_POST['password'])), PASSWORD_BCRYPT); //Clean the data up
}else{
//Error handling code
}
if(!isset($username) || !isset($password)){
//Error handling code
}else{
$stmt = $db->prepare('SELECT fullname FROM members where username= :username and password=:password');
$stmt->execute(array('username':$username,'password':$password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//Code here to make sure there is a row with the number given and all that
//other jazz. In this code I'll assume all went well
if(All_went_well){
//Start your session to store variables you want
session_start();
$_SESSION['fullname']=$row['fullname'];
}
}
}
In your login method, save $username as a session value under $_SESSION['loggedin'] that you can retrieve later like this...
public function login($username,$password){
$hashed = $this->get_user_hash($username);
if($this->password_verify($password,$hashed) == 1){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
return true;
}
}
Then have another method at the bottom of the file that goes something like...
public function get_username(){
if(isset($_SESSION['username'])){
return $_SESSION['username'];
}
}
Then you can call this method like $user->get_username() to get the current logged in users username. Then getting their fullname from the database would require a simple query with "WHERE username = :username". I you can add another method like this to make things easier...
public function get_fullname(){
if(issset($_SESSION['username']){
$stmt = $this->_db->prepare('SELECT fullname FROM members WHERE username = :username');
$stmt->execute(array('username' => $this->get_fullname()));
$row = $stmt->fetch();
return $row['fullname'];
}
}
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!';