Trying to convert mysql to mysqli, not working - php

I have this code, it was originally in mysql() but since it's deprecated and obsolete well i decided to change. Something is clearly not working because when I execute it always says incorrect password/username although it is correct. Database works. Triple checked. Pardon me, i'm a noob at php. here:
<?php
//If the user is logged, we log him out
if(isset($_SESSION['username']))
{
//We log him out by deleting the username and userid sessions
unset($_SESSION['username'], $_SESSION['userid']);
?>
<div class="alert alert-info">You have been logged out securely.</div>
<?php
}
else
{
$ousername = '';
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password']))
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$escapePass = stripslashes($_POST['username']);
$escapeUser = $_POST['username'];
$ousername = stripslashes($_POST['username']);
$username = mysqli_real_escape_string($link, $escapePass);
$password = sha1(stripslashes($_POST['password']));
}
else
{
$username = mysqli_real_escape_string($link, $escapeUser);
$password = sha1($_POST['password']);
}
//We get the password of the user
$query = 'SELECT password, id FROM users WHERE username="'.$username.'" ';
$req = mysqli_query($link, $query);
$dn = mysqli_fetch_array($req);
print $reg;
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysqli_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
?>
#Fred -ii- This:
if(get_magic_quotes_gpc())
{
$escapePass = stripslashes($_POST['username']);
$escapeUser = $_POST['username'];
$passescape = sha1($_POST['password']);
$passescape2 = sha1(stripslashes($_POST['password']));
$ousername = stripslashes($_POST['username']);
$username = mysqli_real_escape_string($link, $escapePass);
$password = mysqli_real_escape_string($link, $passescape2);
}
else
{
$username = mysqli_real_escape_string($link, $escapeUser);
$password = mysqli_real_escape_string($link, $passescape);
}

Just for a quick testing purpose, try this below which is a bare bones method.
You can then slowly build up sanitizing and troubleshoot from thereon.
<?php
$username = $_POST['username'];
$password = sha1($_POST['password']);
$link = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT password, id FROM users
WHERE username = '$username' AND password='$password'";
$result = mysqli_query($link, $query);
if(mysqli_num_rows($result) < 1)
{
echo 'Sorry, your username and/or password was incorrect.';
}
else
{
echo "Welcome!";
}
?>
Footnote: I noticed in your original code that you are using sessions.
I did not see session_start(); in your code, nor any mention of it.
This needs to be at the top of your code and inside all your files used,
which will be needed in order to access anything currently in $_SESSION
More on sessions can be found on the PHP.net Website.
http://www.php.net/session_start

Related

login system not working using php and mysql

so im trying to get my login working which is using php and mysql. i dont no what to replace (mysqli_fetch_array) because before i was using md5 password and changed it to password hash. what i want the code to basically do is when the users correct email and password is inputted the page is redirected to (user-page.php) where the user info will be displayed. im only having problems with the login as the register is working with password hash
<?php
session_start();
require_once "connection.php";
if(isset($_SESSION['username'])!="") {
header("Location: user-page.php");
}
if (isset($_POST['login'])) {
$email = $_POST['email'];
$password = $_POST['password'];
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$email_error = "Please Enter Valid Email ID";
}
$query = "SELECT `password` FROM `users` WHERE `email` = ?";
if(!empty($query)){
if ($row = mysqli_fetch_array($query)) {
$_SESSION['user_id'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SESSION['full_name'] = $row['full_name'];
$_SESSION['email'] = $row['email'];
$_SESSION['gender'] = $row['gender'];
$_SESSION['medical_condition'] = $row['medical_condition'];
header("Location: user-page.php");
}
}else {
}
}
?>
the below code works by checking if the email exits and if the password is correct but only displays if the password is correct or incorrect. is there a way to redirect the user like the code above?
<?php
session_start();
require_once "connection.php";
if(isset($_SESSION['username'])!="") {
header("Location: user-page.php");
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
$password = $_POST['password'];
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$email_error = "Please Enter Valid Email ID";
}
$query = "SELECT `password` FROM `users` WHERE `email` = ?";
$params = array($_POST['email']);
$results = dataQuery($query, $params);
$hash = $results[0]['password']; // first and only row if username exists;
echo password_verify($_POST['password'], $hash) ? 'password correct' : 'passwword incorrect';
}
?>
register.php
<?php
require('connection.php');
if (isset($_POST['username'])){
$username = $_POST['username'];
$full_name = $_POST['full_name'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$medical_condition = $_POST['medical_condition'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
// insert values into the database.
$query = 'INSERT INTO `users` (`username`, `full_name`, `gender`,`email`,`medical_condition`, `password`) VALUES (?,?,?,?,?,?)';
$params = array($username, $full_name, $gender, $email, $medical_condition, $password);
$result = dataQuery($query, $params);
$_SESSION['username'] = $username;
$_SESSION['full_name'] = $full_name;
$_SESSION['email'] = $email;
$_SESSION['gender'] = $gender;
$_SESSION['medical_condition'] = $medical_condition;
if($result){
header("Location: user-page.php");
}
}else{
?>
When login in, after you check if password is valid, you need to fill your Session the same way you would after registering.
It differs from the registering, Instead of receiving all the information via the $_POST attribute, you need to get the information from the database and fill the $_SESSION.
So you would need to select more information from the query
$query = "SELECT * FROM `users` WHERE `email` = ?";
$params = array($_POST['email']);
$results = dataQuery($query, $params);
$hash = $results[0]['password']; // first and only row if username exists;
if ( password_verify($_POST['password'], $hash) )
{
$_SESSION['username'] = $results[0]['username'];
$_SESSION['full_name'] = $results[0]['full_name'];
$_SESSION['email'] = $results[0]['email'];
$_SESSION['gender'] = $results[0]['gender'];
$_SESSION['medical_condition'] = $results[0]['medical_condition'];
header("Location: user-page.php");
}
From my understanding of your question, you're trying to do a redirect with header("Location: user-page.php"); after doing password_verify($_POST['password'], $hash) and storing your user information in $_SESSION.
There is a single issue when using header() function as stated in the documentation :
https://www.php.net/manual/en/function.header.php
Note:
Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.
So you have to actually add the Session ID to the url manually for your session to persist to your next page.
It would look like this:
//https://www.php.net/manual/en/session.idpassing.php
//https://www.php.net/manual/en/function.session-id
//
//EDIT:
//307 Temporary Redirect
//Added slash "/" in front of php page. Better browser recognition.
header("Location: /user-page.php?".htmlspecialchars(SID),TRUE, 307);
//Use exit function to terminate program and make sure it does not perform any other tasks.
exit();

Creating one of two sessions php

Im trying to create two different sessions. One for the admin, the other for normal users. If SQL returns admin_role as 1 = admin. If admin_role as 0 = user.
I have session_start() in the beginning of the document via include('connection.php'). When I press submit on my login form nothing really happens as for now.
if(empty($_POST["username"]) || empty($_POST["password"])){
$error = "Fill in both fields!";
} else {
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect from MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
// Check username and password from database
$sql = "SELECT admin_role FROM user WHERE user_name='$username' AND user_password='$password'";
$result = mysqli_query($db, $sql);
$admin_role = $row['admin_role'];
// If username and password exist in our database then create a session.
// Otherwise echo error.
if(mysqli_num_rows($result) == 1){
if($admin_role == 1){
$_SESSION['admin'];
header("location: logged-in.php");
}
if($admin_role == 0){
$_SESSION['username'];
header("location: logged-in.php");
}
} else {
$error = "Wrong credentials";
}
}

PHP choose another username

I have made a registration PHP file that runs through an authentication and connects to my database that I made in phpMyAdmin. The problem is, I can put in the same username without consequence and it adds to the database, so I could put; dogs as the username and then again put the same.
How can I make it so the user is told; that username already exists choose another one.
Here's my php so far;
Also please tell me where to insert it.
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query($query);
if ($result) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
} else {
?>
You should query the database before inserting any record (user) to users table.
Try the code below:
<?php
$username = mysql_real_escape_string( $username ); //Sql injection prevention
$existance = mysql_query("SELECT username FROM users WHERE username = '" . $username . "'");
if( !$existance ){
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query( $query );
if ( $result ) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
else{
//unsuccessful insertion
}
} else {
//the user existed already, choose another username
}
?>
Create an if-statement where you check if $username exists in the db. If it does, throw an error. If not, continue with the code.
Note
Your code is vulnerable to SQL-injection. Read this post: How can I prevent SQL injection in PHP?
Rewriting my entire answer to a working example. I'm going to assume your post variables are the same as mine: email, password, username
<?php
$errorMessage = "";
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$email1 = $_POST['email'];
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
$username = htmlspecialchars($username);
$connect = mysql_connect("localhost","DBuser", "DBpassword");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("DBName");
$results = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($row = mysql_fetch_array($results)) {
$kudots = $row['username']; }
if ($kudots != ""){
$errorMessage = "Username Already Taken";
$doNothing = 1;
}
$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
while($row2 = mysql_fetch_array($results)) {
$kudots2 = $row2['email']; }
if ($kudots2 != ""){
$errorMessage = "Email Already in use";
$doNothing = 1;
}
//test to see if $errorMessage is blank
//if it is, then we can go ahead with the rest of the code
//if it's not, we can display the error
if ($errorMessage == "") {
$user_name = "DBUsername";
$pass_word = "DBPassword";
$database = "DBName";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$password = quote_smart($password, $db_handle);
$username = quote_smart($username, $db_handle);
if ($username1 == ""){
$errorMessage = "You need a username";
}
if ($password1 == ""){
$errorMessage = $errorMessage . "<br>You need a password.";
}
if (!(isset($_POST['email']))){
$errorMessage = $errorMessage . "<br>You need an email.";
}
$SQL = "SELECT * FROM users WHERE email = $email";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "email already exists";
$doNothing = 1;
}
if ($errorMessage == "") {
$SQL = "INSERT INTO users (email, username, password) VALUES ($email, $username, $password)";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['email'] = "$email1";
$_SESSION['password'] = "$password1";
header ("Location: myaccount.php");
else {
$errorMessage = "Database Not Found";
}
}
OK, now echo $errorMessage right below or above the form, to inform the user that the Email, or Username is taken. I'm pretty sure I have a duplicate function in here for the Email, but this code does work; disregard if somebody says it's vulnerable to SQL injection; this is a working EXAMPLE! If you want to do MySQL real escape string, just Google it. I had to rewrite a couple things because I don't want my full code on a public board, if for some odd reason this doesn't work; send me an eMail(canadezo121#gmail.com) and I'll send you the full page code. (Which WORKS!) This code will probably raise some concerns with other more professional coders, this example gives you a good logical viewpoint of what goes on and how it works. You can adjust it to MySQLi, PDO, etc as you get more familiar with PHP and MySQL.
1 you must verify if the username all ready exists in database (Select)
2 if not exists after you can insert the new user

Using Session and Cookies together for remember me

In my login page I am using Session and Cookies both, session for usual login and cookies when remember me is checked. My code for creating session or setting cookies is:
if(isset($_POST['login'])){
$username = $_POST['user_login'];
$password = $_POST['password_login'];
$stmt = $db->prepare("SELECT * FROM userss WHERE username = :username AND password = :password");
$stmt->execute(array(':username'=>$username,':password'=>$password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$user_db = $row['username'];
$pass_db = $row['password'];
if($username == $user_db && $password == $pass_db) {
$_SESSION['username']=$username;
if ($_POST['rememberme']!=NULL) {
setcookie('username', $username,time()+31556926);
}
header("Location:main.php");
}
and then on any page to create a user fuction I am calling session or cookie like this:
if(isset($_COOKIE['username'])||isset($_SESSION['username'])) {
$username = $_COOKIE['username'];
$username = $_SESSION['username'];
}
Now my problem is:
Even when remember me is checked session is used and not cookies I tested it by exiting my browser. I can't figure out where code has gone wrong.
In the second code if(isset($_COOKIE['username'])||isset($_SESSION['username'])) { is correct but I am not sure how to define username for both different situations also
$username = $_COOKIE['username']; is giving me undefined index username. May be my way of setting cookies has gone wrong.
Replace here
if (isset($_POST['rememberme'])) {
setcookie('username', $username,time()+31556926);
}
And in user functions
if(isset($_SESSION['username']) {
$username = $_SESSION['username'];
}
else if(isset($_COOKIE['username']){
$username = $_COOKIE['username'];
}
else
{
//invalid ---
}

Need help displaying username when user logs in php

So below I have my php code, everything works fine and dandy except when the user logs in and is redirected to the restricted page. When a person signs up, they fill out their first name, email, and password. In the login page it only requires email and password. When they are redirected I want to only display their first name though. I have tried making the session = $result which should return the result of the sql query, but if I do that it doesn't even redirect to the restricted page. What am I doing wrong?
<?php
// DATABASE VARIABLES
$user_name = "";
$pass_word = "";
$database = "";
$server = "";
// CONNECTS TO DATABASE
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
// ACCOUNT INFORMATION
$email;
$password;
$num_rows = 0;
// IF SUBMIT IS CLICKED
if (isset($_POST['submit'])) {
// STORES INPUTS AS VARIABLES
$email = $_POST['email'];
$password = $_POST['password'];
// REMOVES HARMFUL CODE
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
if ($db_found) {
$SQL = "SELECT * FROM accounts WHERE email = '$email' AND password = '$password'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = ?;
header ("Location: loggedin/account.php");
}
else {
session_start();
$_SESSION['login'] = '';
}
}
else {
}
}
?>
Here is what I would do.....
// DATABASE VARIABLES
$user_name = "";
$pass_word = "";
$database = "";
$server = "";
// CONNECTS TO DATABASE
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
// ACCOUNT INFORMATION
$email;
$password;
$num_rows = 0;
// IF SUBMIT IS CLICKED
if (isset($_POST['submit'])) {
// STORES INPUTS AS VARIABLES
$email = $_POST['email'];
$password = $_POST['password'];
// REMOVES HARMFUL CODE
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
if ($db_found) {
$SQL = "SELECT * FROM accounts WHERE email = '$email' AND password = '$password'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
// Grab user name from db
$row = mysql_fetch_row($result);
if ($num_rows > 0) {
// Add to session variable
session_start();
$_SESSION['login'] = $row['username'];
header ("Location: loggedin/account.php");
}
else {
//Either exit or redirect to login failure page.
}
}
else {
This seems alright to me although I cant test at current.
Edit
You may want to have a read on using the Mysqli and PDO connection, it is slightly quicker and definitely more secure, just a suggestion if you have the time. Also prepared statements would definitely be more secure.
This is how I do Login... You must have an ID for each user in mysql and define
$_SESSION['user_id'] = $fetched_id;
and in loggedin/account.php page you can simply make this:
$user_id = $_SESSION['user_id'];
$query = mysql_query("SELECT `first_name` FROM `users` WHERE `id` = '{$user_id}'");

Categories