error multi user php - php

this is the code that have 3 user, the code just running for 2 user,it's in condition idLogin=1 and idLogin=2, i don't know why in condition idLogin=3 it does't work .
<?php
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
$username = $_POST['username'];
$password = $_POST['password'];
$login = $_POST['login'];
if (isset($login)) {
$mysqli = new mysqli("localhost", "root", "", "loginda");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT * FROM login where username='$username' and password='$password'");
$row = $res->fetch_assoc();
$idLogin = $row['id_login'];
$user = $row['username'];
$pass = $row['password'];
$type = $row['type_login'];
if ($user == $username && $pass = $password) {
session_start();
if ($idLogin == "1") {
$_SESSION['mysesi'] = $user;
$_SESSION['myid'] = $idLogin;
echo "<script>window.location.assign('admin.php')</script>";
} elseif ($idLogin == "2") {
$_SESSION['mysesi'] = $user;
$_SESSION['myid'] = $idLogin;
echo "<script>window.location.assign('index.php')</script>";
} elseif ($idLogin == "3") {
$_SESSION['mysesi'] = $user;
$_SESSION['myid'] = $idLogin;
echo "<script>window.location.assign('index2.php')</script>";
} else {
?>
this is code for index2.php
<?php
session_start();
if (!isset($_SESSION['mysesi']) && !isset($_SESSION['myid'])=='3')
{
echo "<script>window.location.assign('login.php')</script>";
}
?>
<!DOCTYPE html>
<html lang="en">
..........
</html>

I think error may be here...
if($user==$username && $pass=$password) // here is single `=` sign
It should be like as:
if($user==$username && $pass==$password) // double `==` for comparasion

I might be wrong, but I don't think that you can check bool isset for $S_SESSION['myid'], while checking its contents within the same if statement. I think you might have to check that the sessions are set first, then check the value of $_SESSION['myid'].
Try this:
if ((!isset($_SESSION['mysesi']) && !isset($_SESSION['myid'])) || $_SESSION['myid'] !='3')
{
echo "<script>window.location.assign('login.php')</script>";
}
You should also consider using PDO objects for MySQL interactions. And even more importantly, you need to sanitize your user inputs below using them in your MySQL Query, if you are going to use mysqli the way you that currently do.
Lastly, you should not be storing your passwords in plain text. There are a number of hashing algorithms available to hash passwords before storing them in your database. However PHP5.5 and up includes the password_hash function to make things easier for you.

Related

Only echo works in this code in this if statement (PHP)

$con = mysqli_connect('localhost', 'login', '*mypass*', 'login');
$check = "SELECT * FROM users";
$rs = mysqli_query($con, $check);
if(isset($_POST['submit'])) {
$username = strtolower($_POST['username']);
$password = hash('sha512', $_POST['password']);
if($username && $password){
while($data = mysqli_fetch_array($rs)){
if($username == $data[1]){
if($password == $data[2]){
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
$exp = time() + (60*60*24*365);
setcookie('user', $username, $exp);
echo "test";
header("location: dash.php");
exit();
} else {
error("Incorrect Password");
}
}
}
} else {
error("Please insert your username and password");
}
}
In this code, the content of the if statement ( if($password == $data[2]) ) doesn't run correctly: only the echo function works, all the other doesn't!
Is there a solution to this issue?
I use PHP 7.0
POST:
echo "test"; was added only for testings purposes, the code doesn't work with or without it.
Looking at this part:
if($username && $password){
while($data = mysqli_fetch_array($rs)){
if($username == $data[1]){
if($password == $data[2]){
You should be careful when reading $data. Put simply, the $data array is indexed on a per-row basis starting from 0, so $data[1] and $data[2] refer to the entire second and third resultset rows, but you're not actually reading any result fields.
The right and cleaner way would be:
if($username && $password){
$data = mysqli_fetch_array($rs);
foreach ($data as $row)
{
$username = $row['field_name_with_username];
$password = $row['field_name_with_password];
... then whatever you need to do afterwards with those variables
}
If you rather stay away from the foreach looping, you can use while or for, but you need to define an interation counter (i.e. $i = 0; before entering the loop and $i++; just before the end of each iteration) and on each pass access $data[$i]['field_name_with_username'] and $data[$i]['field_name_with_password']
This is not an answer but something to try to check sessions are working.
Place the following code in its own file:
<?php
session_start();
if(isset($_SESSION['test_counter'])) {
$_SESSION['test_counter']++;
} else {
$_SESSION['test_counter'] = 1;
}
echo $_SESSION['test_counter'];
It should first display 1, and then increment the integer upon refresh.

$_SESSION["id"] is always zero in the database

I have been trying to solve this issue couldn't, tried reading from asked questions but couldn't get it. I started the session and required it in another page but when ever i want to use it to insert some text base on the current session id, it is always zero in the database. Please,explain to me, maybe i miss understood it. Thanks!
<?php
ob_start();
session_start();
if(isset($_SESSION['$user_id']) && !empty($_SESSION['$user_id']))
{
return true;
}
else
return false;
?>
include.php
<?php
include ("login._form.php");
require ("include.php");
require("require.php");
if ($_SERVER["REQUEST_METHOD"]== "POST")
{
$username = mysqli_real_escape_string($link, $_POST["user"]);
$password = mysqli_real_escape_string($link,$_POST["password"]);
if(empty($username) || empty($password))
{
die();
}
$row = mysqli_query($link,"SELECT * FROM `users` WHERE username ='$username'");
if($row === false)
{
echo "Query Error";
}
while($fetch = mysqli_fetch_array($row)){
if($username == $fetch["username"] && $password == $fetch["password"])
{
$_SESSION["id"] = $id;
header('Location:index.php');
}
else
die("user does'n exist");
}
mysqli_close($link);
}
login.php
?>
require("include.php");
include ("yd_sendpage_form.php");
require("require.php");
if ($_SERVER["REQUEST_METHOD"]== "POST")
{
$user_id = $_SESSION["id"];
$text = mysqli_real_escape_string($link,$_POST["text"]);
if(empty($text))
{
die("Field Can't Be Empty!");
}
$insert = mysqli_query($link,"INSERT INTO `text`(`id`, `user_id`, `text`) VALUES ('$user_id','$user_id','$text')");
}
?>
yd_sendpage.php
Change
if(isset($_SESSION['$user_id']) && !empty($_SESSION['$user_id']))
to
if(!empty($_SESSION['id']))
And don't forget about SQL injection, your code is vulnerable to it.
More information about SQL injection in your code
$_SESSION["id"] was not set, so i changed $_SESSION["id"] to $_SESSION["user"] = $username in the login.php and other pages to $_SESSION["user"] and that works. Thanks!

If and else statement , test on the user account status

I want to make test on the status of the user account.
If the account is active I redirect him to the user page
If the account is not active I redirect him to login page again with an error
Here’s my code
<?php
require('conexion.php');
$username = '';
$password = '';
if (isset($_POST['username']) || !empty($_POST['username']))
$username = $_POST['username'];
if (isset($_POST['password']) || !empty($_POST['password']))
$password = $_POST['password'];
$q1 = "select * from user where username='" . $username . "' and password='" . $password . "' ";
$r1 = $db->query($q1);
$i = 0;
echo $q1;
while ($d1 = $r1->fetch()) {
$i++;
//$id_perso = $d1['id_perso'];
$type = $d1['type'];
$nom = $d1['nom'];
$prenom = $d1['prenom'];
$statut = $d1['statut'];
$user_id = $d1['id_user'];
}
if ($i == 1) { // START IF
session_start ();
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['type'] = $type;
$_SESSION['nom'] = $nom;
$_SESSION['prenom'] = $prenom;
$_SESSION['statut'] = $statut;
$_SESSION['user_id'] = $user_id;
if ($statut = 'actif') {
if ($_SESSION['type'] == 'admin') {
$path = "admin/index.php";
}
if ($_SESSION['type'] == 'professeur') {
$path = "professeur/index.php";
}
if ($_SESSION['type'] == 'doctorant') {
$path = "doctorant/index.php";
}
header("Location:".$path);
} elseif ($statut = 'inactif') {
header("location:login.php?inactif");
}
} else {
header("location:login.php?error=1");
}
?>
Why don't you use a boolean, should be easier.
/*
1. Get Status from Database
2. When the user is active, you set the boolean true, else false. */
$booleanVar = false;
if($booleanVar) {
// user is active
} else {
// user is inactive
}
EDIT:
Redirecting with header works like this, I believe its Case Insensitive:
header('Location: somesite.php?abc');
Also you have to check values with "==" (for equal) or "===" (for identical)
You could simply get the same result if you do this with a simple query:
You check if the password and the username matches AND check if the account has been activated.
$sql = 'SELECT `id` FROM `user` WHERE `username` = '$username' AND `password` = '$password' AND `statut` = 1'
You then can run the query and check if number of rows is greater than 0.
$sql = $db->query($sql);
$results = $sql->fetch();
if (count($results) > 0) {
// Account is activated
} else {
header("location: login.php");
exit;
}
You are also vulnerable to SQL-injections by inserting your variables directly into your query, wich Edhurtig noticed! The best way to prevend SQL-injections is to use PDO prepared statements.
First and foremost: DO NOT STORE PASSWORDS IN PLAINTEXT. Do some research into secure hashing algorithms (not md5) or use a third party authentication service like Google, Facebook, Github, ect.
Second: This code is vulnerable to SQL injection via $_POST['username'] and $_POST['password']
Also it was a bit unclear what was being asked but I felt it was important to point out the aforementioned issues because they are so security critical.
Here is what I was able to cleanup. I would strongly recommend using a third party authentication service though
<?php
require('conexion.php');
$salt = "random_string";
$username='';
$password='';
if (isset($_POST['username'])||!empty($_POST['username'])) $username = $_POST['username'];
if (isset($_POST['password'])||!empty($_POST['password'])) $password = $_POST['password'];
$hashed_password = some_hashing_function_1000_times($password, $salt);
$q1="SELECT * FROM user WHERE `user`.`username` = '%s' AND `user`.`password` = '%s' LIMIT 1";
// I hope that $db has a prepare function, it prevents SQL injections from $_POST['username'] and $_POST['password']
$sql = $db->prepare($q1, $username, $hashed_password);
$r1= $db->query($q1);
$user = $r1->fetch();
if( $user ) { // START IF
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['type'] = $type;
$_SESSION['nom'] = $nom;
$_SESSION['prenom'] = $prenom;
$_SESSION['statut'] = $statut;
$_SESSION['user_id'] = $user_id;
if($statut == 'actif'){
if($_SESSION['type']=='admin') { $path="admin/index.php"; }
if($_SESSION['type']=='professeur'){ $path="professeur/index.php"; }
if($_SESSION['type']=='doctorant') { $path="doctorant/index.php"; }
header("Location: " . $path);
exit();
}
else if ($statut == 'inactif') {
header("Location: login.php?inactif");
exit();
}
}
header("Location: login.php?error=1");
exit();
// No Closing PHP tag at end of file

Login PHP keeps returning invalid username or password even if the fields are correct?

So basically, when I press login on my form, even if my username and password are correct in the input fields, I keep getting the invalid username or password error. I am unsure how to fix this, as everything looks correct in my code. How would I fix this so I can log in? Here is the code:
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "users";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error)
{
die("Connection failed: " . $mysqli->connect_error);
}
else
{
if (isset($_POST["username"]) && isset($_POST["password"]))
{
$username = (string)$_POST["username"];
$password = (string)$_POST["password"];
$result = $mysqli->query("SELECT * FROM `users` WHERE `username`='$username'");
while($row = $result->fetch_assoc())
{
if ($username == $row['$username'] && $password == $row['password'])
{
$regKey = $row['regKey'];
$_SESSION["reg"] = $regKey;
die("YOU DID IT");
}
else
{
$mysqli->close();
die("Error, invalid username or password");
}
}
}
}
Thank you for taking your time to help.
Yes, as HawasKaPujaari say you were trying to fetch an invalid column.
But also, I think you can have some problems with your session, you need to initialize, like this:
#session_start();
Just before this:
$_SESSION["reg"] = $regKey;
Good luck!
Instead of this:
if ($username == $row['$username'] && $password == $row['password'])
try this:
if ($username == $row['username'] && $password == $row['password'])
You were most probably trying to fetch an invalid column $row['$username'] from the database.
What is the need of if(condition inside while loop).? Check your condition in sql query only.
.
.
.
$username = $_POST["username"];
$password = $_POST["password"];
$result = mysqli->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$CountResult=mysql_num_rows($result);
if($CountResult==1)
{
while($row = $result->fetch_assoc())
{
$regKey = $row['regKey'];
$_SESSION["reg"] = $regKey;
die("YOU DID IT");
}
}
else
{
$mysqli->close();
die("Error, invalid username or password");
}
.
.
.

PHP If Statement Issue

I am working on something, but with my if statements, it will say "test" no matter what, not following the other if statements. Help please, heres my code:
<?php
$userr = $_POST['user'];
$user = ucwords($userr);
$pass = $_POST['pass'];
if ($submit)
{
if ($userr && $pass)
{
if ($user == "Admin" && $pass == "password")
{
echo "Logged in";
}
else
{
echo "Fill in all fields";
}
}
else
{
echo "Submit!";
}
}
else
{
echo "test";
}
?>
Where are initializing your $submit?
By a look at your code, I think you need:
$submit = $_POST['submit'];
That's most likely because $submit always evaluates to false.
Make sure that $submit is defined and is what you expect it to be.
Also, if $user == 'false' your script will break without warning.

Categories