PHP MYSQL connection with query inside IF statement - php

SOLVED:
There is a conlict with my declaring of variables. It turns out i declare a $password in my connect_database, but also in my account script meaning the $password is always set and therefore always skips pas the if's to the end...and since this is work in progress it's the same simple password as my account login...
ORIGINAL:
I have a problem with queries inside if statements in PHP. I'm doing an account update script.
I require the connection to the database at the top and then depending on the result from the POST, I do diffrent queries in some if statements.
If it runs passed all IF statements it runs a query at the end.
If it's caught by any of the if's, a query is made and I want the script to redirect with a message code and terminate the code with an exit.
The problem is the script will not exit after an if execution is made. It does the query but it runs all the way to the end - no redirect and exit...
I found a workaround which requires the database to be required inside the if statements and then again at the bottom instead of only at the top, but my initial idea was to just include it at the top and use the connection in the if statement and again at the bottom.
Can anyone explain why one works and the other doesn't?
It's not a big deal. I just don't understand why...
Thanks a lot
This doesnt work (Require database outside of the IF statement):
<?php
session_start();
if(!isset($_SESSION["user"])) {
header("location: ../../../login/login_form.php");
exit;
}
$user = mysql_real_escape_string($_POST['user']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$id = $_SESSION['user_id'];
//Display if user and email is blank - try again---------------
if($user==NULL || $email==NULL){
header('location: ../../../index.php?show=account&message=1');
exit;
}
require_once('../../connect_database.php');
//Check if password is blank - meaning only updating user and email -----
if ($password==NULL){
$query = "UPDATE user SET user='$user', email='$email' WHERE id=".$id;
mysql_query($query) or die(mysql_error());
header('location: ../../../index.php?show=account&message=0');
mysql_close();
exit;
}
//Display if password less than 8 characers----------------
if(strlen($password)<8 && $password!=NULL){
header('location: ../../../index.php?show=account&message=2');
mysql_close();
exit;
}
//Run this if everything is to be changed incl. password-------
$query = "UPDATE user SET user='$user', password=md5('$password'), email='$email' WHERE id=".$id;
mysql_query($query) or die(mysql_error());
mysql_close();
header('location: ../../../index.php?show=account&message=0');
?>
This works (Require database inside of the IF statement and then again at the bottom):
<?php
session_start();
if(!isset($_SESSION["user"])) {
header("location: ../../../login/login_form.php");
exit;
}
$user = mysql_real_escape_string($_POST['user']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$id = $_SESSION['user_id'];
//Display if user and email is blank - try again---------
if($user==NULL || $email==NULL){
header('location: ../../../index.php?show=account&message=1');
exit;
}
//Check if password is blank - meaning only updating user and email ----
if ($password==NULL){
require_once('../../connect_database.php');
$query = "UPDATE user SET user='$user', email='$email' WHERE id=".$id;
mysql_query($query) or die(mysql_error());
header('location: ../../../index.php?show=account&message=0');
mysql_close();
exit;
}
//Display if password less than 8 characers------------------
if(strlen($password)<8 && $password!=NULL){
header('location: ../../../index.php?show=account&message=2');
exit;
}
//Run this if everything is to be changed incl. password----------
require_once('../../connect_database.php');
$query = "UPDATE user SET user='$user', password=md5('$password'), email='$email' WHERE id=".$id;
mysql_query($query) or die(mysql_error());
mysql_close();
header('location: ../../../index.php?show=account&message=0');
?>

The problem is the script will not exit after an if execution is made.
you are wrong. exit operator is plain and simple and always work.
How do you know the query was executed? Any debug output you've got?
Thre are many issues with your code but at least make it less repetitive and moire consistent
<?php
session_start();
if(!isset($_SESSION["user"])) {
header("location: ../../../login/login_form.php");
exit;
}
$user = $_POST['user'];
$password = $_POST['password'];
$email = $_POST['email'];
$id = $_SESSION['user_id'];
//Display if user and email is blank - try again---------------
if (!$user || !$email) {
$message=1;
}
//Display if password less than 8 characers----------------
elseif ($password && strlen($password)<8){
$message=2;
} else {
require_once('../../connect_database.php');
$user = mysql_real_escape_string($user);
$email = mysql_real_escape_string($email);
if ($password) {
$password = "password='".md5($password)."',";
}
$query = "UPDATE user SET user='$user',$password email='$email' WHERE id=".$id;
mysql_query($query) or trigger_error(mysql_error());
$message = 0;
}
header("location: ../../../index.php?show=account&message=$message");
Also note
you cannot use mysql_real_escape_string before connect
using relative paths (all those dots) considered bad practice, especially with location

I believe that location is case sensitive. Try changing it to
header("Location:../../../index.php?show=account&message=0");

Ok here is what i suggest :
Replace all exit with die()
And if that doesn't work try replacing all the Location headers with this :
<script>
window.location='/path/to/your/redirection';
</script>
Let me know if that helps in any way :)

Related

I'm trying to create a login system

Hello Stackoverflow community,
I'm trying to code a login system within php. Until now everything worked, but now I wanted to integrate a function, that allows accounts to be banned. But the problem is, that this doesn't work out that well.
So I've got my MySQL table, which looks like this:
And then there is my login.inc.php which looks like this:
<?php
include 'essentials.inc.php';
$username = $_POST["username"];
$password = $_POST["password"];
$sql = "SELECT * FROM accounts WHERE username='$username' AND password='$password'";
$result = $conn->query($sql);
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
if ($row['status'] == "Banned") {
header("Location: ../login.php?error=2");
}
$id2 = $row['id2'];
$_SESSION['id2'] = $id2;
header("Location: ../index.php");
} else {
header("Location: ../login.php?error=1"); // wrong un or pw
}
?>
Now it should redirect to login.php?error=2, if the status equals 0. The problem is, that it just ignores that case. If the status equals 0, it just logs the account in as it wouldn't be there.
Thank you for your help!
Shouldn't status = 0 instead 'Banned' or I am missing something
if ($row['status'] == 0) {
header("Location: ../login.php?error=2");
}
Make sure you are checking for the correct value like #bri suggested. Your condition has to match your database options for status. Also, try putting exit; or exit(); after your location header. Sometimes the script keeps running before the page redirects.

Php login code, data does not match

Here is my code that I made when I tried to make a login page to my site. I get wrong details everytime I try to login, I have checked the details several times so that they match, I do get a clear dbconnection so there is not a problem with that either. I do not have an md5 encryption so that I have thought of too... I use LONGTEXT as datatype in my mysql database for storage of name and password. I got 3 rows of information in the table users of the database. ID, Name, password, named exactly as I have written.
I hope this was enough information to get some help?
Thanks in advance!
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_SESSION['user'])!=""){
header("Location: index.php");
}
if(isset($_POST['login'])){
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res = mysql_query("SELECT * FROM users WHERE Name='$email'");
$row = mysql_fetch_array($res);
if($row['password']==$upass){
$_SESSION['user'] = $row['user_id'];
header("Location: index.php");
} else {
?>
<script>alert('wrong details');</script>
<?php
}
}
?>
You don't need to do this because will not pass this to the query anyway.
$upass = mysql_real_escape_string($_POST['pass']);
The value of the password is not equal to the value of the escaped password. So this will not be accurate.
if($row['password']==$upass){}
You could just do something like
if($row['password']==$_POST['pass']){}
I would suggest following fixes to your script..
1) Make sure that the name should be unique in your db table..
e.g. if some one has already registered with name as "admin" then do not allow any other person use that as username( or name in your case) to use.
2) Check name and password both in the query it self.
See the below modified code..
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_SESSION['user'])!="")
{
header("Location: index.php");
}
if(isset($_POST['login']))
{
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res = mysql_query("SELECT * FROM users WHERE Name='$email' AND password = '$upass' ");
if($res) // check if there is any error in the query
{
if(mysql_num_rows($res) == 1) // check for the number of Name - password pair
{
$row = mysql_fetch_array($res);
$_SESSION['user'] = $row['user_id'];
header("Location: index.php");
}
else
{
?>
<script>alert('wrong details');</script>
<?php
}
}
else
{
echo "Error while log in: ".mysql_error();
}
}
?>
Note:
1) Stop using mysql_. They are deprecated Use mysqli_ or PDO
2) Make sure that you have used proper columns names in PHP code, similar to those in the db table.

Users still can login although email and password that insert is wrong,why?

I am quite new in php language..currently i am working on a login and registration system.but i dont know why the users still can login to the although the email and password insert is wrong,since i already make all the validation.So,guys,pls help me to see my code,see whether where the problem is.
here is my code
<?php
include('config.php');
session_start();
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$email = $_POST['email'];
$password = $_POST['password'];
if($email&&$password){
//declare variable
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='$email' Password=''$password");
$numrows = mysqli_num_rows($query);
//when user correct input,check the data
if($numrows !== 0) {
while($row=mysqli_fetch_assoc($query)){
$dbemail=$row['Email'];
$dbpassword=$row['Password'];
}
//if username and password match
if($dbemail=$email&&$dbpassword=$password)
{
$SESSION['$email']="$email";
header('Location:user.html');
}
else
{
$errors['notcorrect'] = "Email or password not correct";
}
}
//when insert wrong data
else{
$errors['notexists'] = "This email doesn't exists";
}
}
//when user didnt enter anything
else{
$errors['nothing'] = "Please enter your email and password";
}
}
?>
any idea?
Let's examine these in detail:
Password=''$password"
$SESSION
if($dbemail=$email&&$dbpassword=$password)
WHERE Email='$email' Password=''$password")
$_SESSION['$email']="$email";
$password is outside your quotes.
Then $SESSION is missing an underscore between the $ and SESSION.
This is also a superglobal.
Then you're "assigning" using 1x = sign instead of "comparing" with if($dbemail=$email&&$dbpassword=$password)
Use 2x == signs.
You're missing an AND for WHERE Email='$email' Password=''$password")
WHERE Email='$email' AND Password='$password'");
You should also, and is recommended to add exit; after header.
header('Location:user.html');
exit;
Otherwise, your code risks in continuing to execute.
$_SESSION['$email']="$email"; there is a dollar sign in ['$email']
It needs to read as ['email'].
Sidenote:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Footnote(s):
In regards to Location:user.html are you sure you want to use an .html file? If you're not instructing Apache to treat .html files as PHP and with no conditional statement to check if the session is set and equal to what you've assigned to it, then anyone can access that file.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
It is recommended to use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
As the chinese proverb goes: "Show a man how to fish, feed him for life."
Update this
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='$email' AND Password='$password' ");
And also correct the session super global from $SESSION to $_SESSION
You are doing an assignment here where you should be doing a comparison:
if($dbemail=$email&&$dbpassword=$password)
Should be
if($dbemail == $email && $dbpassword == $password)
Whitespace makes things more readable.
the error in select query you forgot and operator
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='{$email}' AND Password='{$password}' ");
And change the equle operator in if statment with === like this
if($dbemail===$email&&$dbpassword===$password)
I hope that works successfully
Update your code
<?php
include('config.php');
session_start();
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$email = $_POST['email'];
$password = $_POST['password'];
if($email&&$password){
//declare variable
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='$email' AND Password='$password'");
$numrows = mysqli_num_rows($query);
//when user correct input,check the data
if($numrows !== 0) {
while($row=mysqli_fetch_assoc($query)){
$dbemail=$row['Email'];
$dbpassword=$row['Password'];
}
//if username and password match
if($dbemail==$email && $dbpassword==$password)
{
$_SESSION['$email']="$email";
header('Location:user.html');
die();
}
else
{
$errors['notcorrect'] = "Email or password not correct";
}
}
//when insert wrong data
else{
$errors['notexists'] = "This email doesn't exists";
}
}
//when user didnt enter anything
else{
$errors['nothing'] = "Please enter your email and password";
}
}
?>

How to retrieve information from a record in a database in PHP 5.5?

I am mostly confused about the new php 5.5, I apologize for any inconvenience.
I am trying to get information from whomever logs in, so for example if I log in with an email, I'd like the website to get my first name and do a "Welcome, Shinji!".
$conn = mysqli_connect('localhost','root','');
$db = mysqli_select_db($conn , 'session_start');
$user = $_POST['user'];
$pass = $_POST['pass'];
$query = mysqli_query($conn , "SELECT * FROM `info_table` WHERE '$user' = `user` AND '$pass'=`password`") or die(mysqli_error($conn));
$rows = mysqli_num_rows($query);
if($rows == 1){
#$query2 = mysqli_query($conn , "INSERT INTO `who_logged` (`name`) VALUES ('$user')") or die(mysqli_error($conn));
#$rows = mysqli_num_rows($query);
session_start();
$_SESSION['username'] = $_POST['user']; // store username
$_SESSION['password'] = $_POST['pass']; // store password
$query2 = mysqli_query($conn ,"SELECT `name` FROM `info_table` WHERE '$user' = `user`") or die(mysqli_error($conn));
$result = mysqli_num_rows($query2);
while ($row = mysql_fetch_assoc($result)) {
$_SESSION['name'] = $row['name'];//I thought to try setting the name to the Session variable, but does not work
}
header('Location: next_page.php');
exit();
}else{
echo "Wrong username or password.";
}
I tried to set the name to a session variable, but if there is a more efficient way please say so! (This current code works, except the name setting to session.
You have your column(s) and values mixed up in order.
It's column first, then the value and not the other way around.
Change both:
WHERE '$user' = `user` AND '$pass'=`password`
to:
WHERE `user` = '$user' AND `password`='$pass'
Plus, you're mixing MySQL APIs. Those different APIs do not intermix with each other.
Change mysql_fetch_assoc to mysqli_fetch_assoc
I noticed you are using sessions; make sure session_start(); is indeed loaded.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Also, add or die(mysqli_error($conn)) to mysqli_query()
Your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.
EDIT:
Try the following instead and it will get you started. Please read my footnotes concerning the use/storage of plain text passwords.
Sidenote: I removed $_SESSION['password'] = $pass; // store password
do not do this, it's insecure.
Plus, do not put anything "above" the PHP below, such as HTML etc., otherwise, you will receive a warning about headers already sent.
<?php
$conn = mysqli_connect('localhost','root','');
$db = mysqli_select_db($conn, 'session_start');
$user = stripslashes($_POST['user']);
$user = mysqli_real_escape_string($conn,$_POST['user']);
$pass = stripslashes($_POST['pass']);
$pass = mysqli_real_escape_string($conn,$_POST['pass']);
$query = mysqli_query($conn , "SELECT * FROM `info_table`
WHERE `user` = '$user' AND `password`='$pass'")
or die(mysqli_error($conn));
$num_rows = mysqli_num_rows($query);
if($num_rows > 0){
session_start();
// it's not really needed
// we are pulling it from $row['user'] in the while loop
// and setting it to $_SESSION['username']
// $_SESSION['username'] = $user; // store username
while ($row = mysqli_fetch_assoc($result)) {
$_SESSION['username'] = $row['user'];
}
// for testing only. Do not use with header
// echo $_SESSION['username'];
header('Location: next_page.php');
exit();
}
// do not place any echos here, only the else statement
else{
echo "Wrong username or password.";
}
next_page.php
<?php
session_start();
if(isset($_SESSION['username'])){
echo $_SESSION['username'];
}
else{
echo "Not logged in.";
}
Footnotes
It is highly recommended that you do not store passwords in plain text.
Visit the following Website:
http://daveismyname.com/login-and-registration-system-with-php-bp
It contains a full registration/login/verification system as well as using PDO with prepared statements and PHP's password_hash() function, which is highly recommended.
Since you are using PHP 5.5, then you will benefit from these features.

php login authentication failing

I'm relatively new to php, and I'm trying to write a really simple login script. I've got the basic functionality down, but I can't login to the system. My login script is below, and my registration script is below as well.
checklogin.php
include_once 'inc/db.inc.php';
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
try {
$sql="SELECT id, username, password FROM users WHERE username='$username' and password='$password'";
$result = $pdo->query($sql);
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count == 1){
// Register $username, $password and redirect to file "index.php"
session_register("username");
session_register("password");
header("Location: index.php");
}
else {
header("Location: login.php?invalid=1");
}
}
catch (PDOException $e) {
echo $e;
}
ob_end_flush();
?>
checkreg.php
include_once 'inc/db.inc.php';
//This makes sure they did not leave any fields blank
if (!$_POST['username'] | !$_POST['password'] | !$_POST['passwordconf'] ) {
die('You did not complete all of the required fields');
}
if ($_POST['password'] != $_POST['passwordconf']) {
die('Your passwords did not match. ');
}
$_POST['password'] = md5($_POST['password']);
if (!get_magic_quotes_gpc()) {
$_POST['password'] = addslashes($_POST['password']);
$_POST['username'] = addslashes($_POST['username']);
}
$username = $_POST['username'];
$password = $_POST['password'];
try {
// now we insert it into the database
$sql = "INSERT INTO users(username,password) VALUES ('$username','$password')";
$result = $pdo->exec($sql);
header("Location: index.php");
} catch (PDOException $e){
echo $e;
}
?>
I know that the registration is writing to the database, but everytime I attempt a valid login I receive my invalid credentials flag. Anything you can do to help me would be awesome. Thank you.
Your issue could be with session_register(), depending on the version of PHP you're using. Try putting
session_start();
At the top of checklogin.php, then using
...
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
...
instead of session_register().
First you should clear some things out:
1.
if (!$_POST['username'] | !$_POST['password'] | !$_POST['passwordconf'] ) {
die('You did not complete all of the required fields');}
it should be && and not |.
In your code there's nowhere to check if username exists or not, so i'm guessing that you have multiple users with the same username. Before inserting in your checkreg.php, you should fist check if the username exists or not.
in your checklogin.php change if($count == 1) to if($count > 0)
If this not helped could you give me more information like database data (the data that is in your database now)
<?php
// Use of session_register() is deprecated
$barney = "A big purple dinosaur.";
session_register("barney");
// Use of $_SESSION is preferred, as of PHP 4.1.0
$_SESSION["zim"] = "An invader from another planet.";
// The old way was to use $HTTP_SESSION_VARS
$HTTP_SESSION_VARS["spongebob"] = "He's got square pants.";
?>
Warning:
This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
Couple of things to try:
1) The session_register function call is deprecated. http://php.net/manual/en/function.session-register.php. You really ought to be using $_SESSION if at possible.
Something like this:
$_SESSION["username"] = $username;
$_SESSION["password"] = "validated"; // md5 is variable so you can't easily check for it on next page render
2) When testing for the values, you don't want $_POST, you want to use $_SESSION again on the next page render. Something like this:
if ("validated" == $_SESSION["password"]) {
// You're logged in...
}
3) Note, for the $_SESSION array to be populated you must call session_start(); once and only once before use. (http://www.php.net/manual/en/function.session-start.php for more.)
4) I know this is sample code, but SQL Injection attack possible. Need to escape those variables.
$sql="SELECT id, username, password FROM users WHERE username='$username' and password='$password'";

Categories