PHP not detecting session variable value properly - php

I am trying to make a PHP login and make it show a logout button if logged in and show the login form if not logged in. Here is the form and button showing code:
<?php if ($_SESSION["login"] == "1") { ?>
<form class="form-signin" method="post">
<h2 class="form-signin-heading">You are signed in!</h2>
<input type="hidden" name="op" value="logout">
<button class="btn btn-lg btn-primary btn-block" type="submit">Log out</button>
</form>
<?php } else { ?>
<form class="form-signin" method="post">
<h2 class="form-signin-heading">Sign in</h2>
<input type="text" class="form-control" placeholder="Username" name="user" required="" autofocus="" style="margin:2px 0">
<input type="password" class="form-control" placeholder="Password" name="pass" required="" style="margin:2px 0">
<input type="hidden" name="op" value="login">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
<?php }; ?>
Here is the code that starts the session and sets the variable login:
if (isset($_REQUEST["user"]) && isset($_REQUEST["pass"]) && isset($_REQUEST["op"]) && $_REQUEST["op"] == "login") {
$user = $_REQUEST["user"];
$pass = $_REQUEST["pass"];
$con = mysql_connect("localhost", USER, PASS);
if (!$con) {
die("Could not connect: " . mysql_error());
}
mysql_select_db("reddit", $con);
$sql = mysql_query("SELECT username from t120937_users WHERE t120937_users.username = '" . $user . "' AND t120937_users.password = '" . $pass . "';");
if (mysql_num_rows($sql) > 0) {
session_start();
$_SESSION["login"] = "1";
header("Location: /~rauno.sams/");
} else {
echo "Incorrect login information :(";
}
mysql_close($con);
}
if(isset($_REQUEST["op"]) && $_REQUEST["op"] == "logout") {
$_SESSION["login"] = "";
session_destroy();
header("Location: /~rauno.sams/");
}
However, the login form is displayed every time and I don't know why.

Your select statement has an extra ; in it. So your mysql_num_rows is 0, which is not logging you in.

Related

Redirect to login.php if not logged in

I'm a beginner and need some help with my code.
If I enter the webpage index.php, I want to be redirected to login.php if I'm not logged in.
I'm using this code and it works so I redirects to login.php, but I can't log in. I'm stuck at login.php.
I have this code in my index.php
<?php
if(isset($_SESSION['userId'])) {
// comment
} else {
header("Location:login.php");
}
?>
Parts of my login.php
<?php
include('template.php');
if (isset($_POST['username']) and isset($_POST['password'])) {
$name = $mysqli->real_escape_string($_POST['username']);
$pwd = $mysqli->real_escape_string($_POST['password']);
$query = <<<END
SELECT username, password, user_id FROM users4project
WHERE username = '{$name}'
AND password = '{$pwd}'
END;
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_object();
$_SESSION["username"] = $row->username;
$_SESSION["user_id"] = $row->user_id;
header("Location:index.php");
} else {
echo "Wrong username or password. Try again";
}
}
$content = <<<END
<form action="login.php" method="post">
<div class="form-group">
<input type="text" class="form-control form-control-user" name="username" required placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-user" name="password" required placeholder="Password">
</div>
<div class="form-group">
<div class="custom-control custom-checkbox small">
<input type="checkbox" class="custom-control-input" id="customCheck">
<label class="custom-control-label" for="customCheck">Remember Me</label>
</div>
</div>
<input type="submit" value="Login" class="btn btn-primary btn-user btn-block">
</form>
END;
echo $navigation;
echo $content;
?>
my template.php
session_name('Website');
session_start();
$host = "localhost";
$user = " ";
$pwd = " ";
$db = " ";
$mysqli = new mysqli($host, $user, $pwd, $db);
isset($_SESSION['userId'] !== $_SESSION["user_id"]
aside from the major security issues, you're not comparing the right session name
(for clarity)
You check
<?php
if(isset($_SESSION['userId'])) {
// comment
but you set
if ($result->num_rows > 0) {
....
$_SESSION["user_id"] = $row->user_id;
.....
PappaJ says "pick a naming convention, and stick with it"

Unable to retrieve data from DB and using $_SESSION variable

I've been working on a project that has to do with renting houses. Visitors can register or log-in, and only logged-in users can Add a house for rental. Each user has his own profile showing his username, email and accommodations he has uploaded for rental.
My problem is that I cannot retrieve the email of the logged in user. Also, on my MySQL DB I'm using a foreign key in my accom(modation) table, which references the primary key(USER-ID) of the users. The key fails to match the USER-ID.
Any advice would be really helpful. Thank you a lot in advance.
Posting some of the code below:
register.php
<?php include('server.php') ?>
<? php
if (isset($_SESSION['username'])) {
$_SESSION['msg'] = "You're now logged in.";
unset($_SESSION["register.php"];
header('Location: user_index.php');
}
?>
<!DOCTYPE html>
<html>
<link href="https://fonts.googleapis.com/css?family=Eater" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="mystyle.css">
<body>
<p id="pagetitle">Booking Planet </p>
<div class="navbar" id="topnav">
<button onclick="document.getElementById('id01').style.display='block'"
style="width:auto;">Login</button>
<button onclick="document.getElementById('id02').style.display='block'"
style="width:auto;">Register</button>
HOME
</div>
<?php
$db = mysqli_connect('localhost', 'root', '', 'registration');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($db,"SELECT * FROM accom");
echo "<p> </p>";
echo "<div class='acclist'> Explore some fairytale destinations.. </div>";
echo "<ul>";
while($row = mysqli_fetch_array($result))
{
$image=$row['image'];
$target = "images/".basename($image);
echo "<img src='" . $target . "' width=800 height=500/>";
echo "<li id='title'><b>" . $row['title'] . "</b></li>";
echo "<li> Description: <i>" . $row['description'] . "</i></li>";
echo "<li> Address: <i>". $row['address'] . "</i></li>";
echo "<li> Available from: <i>" . $row['checkin'] . "</i></li>";
echo "<li> Available until: <i>" . $row['checkout'] . "</i></li>";
?><button onclick="document.getElementById('id01').style.display='block'"
type='button' class='bookbtn'>Log-in to book now!</button>
<?php
echo "<li><img src='sepline.png' width=1500 height=75> </li>";}
echo "</ul>";
mysqli_close($db);
?>
</div>
<div id="id01" class="modal">
<? php include('errors.php'); ?>
<form action="" method="post" class="modal-content animate" name="login" >
<div class="logocontainer"> Booking Planet
</div>
<h3> Account Log-in. </h3>
<div class="container">
<? php echo $errors; ?>
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password"
required>
<button type="submit" name="login_user">Login</button>
</div>
<div class="container">
<button type="button" class="cancelbtn" id="cncl1">Cancel</button>
</div>
</form>
</div>
<!-- REGISTRATION -->
<div id="id02" class="modal">
<form action="" method="post" class="modal-content animate" name="register"
>
<div class="logocontainer"> Booking Planet
</div>
<h3> Create an account. </h3>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Name</b></label>
<input type="text" placeholder="Enter your Name!" name="name" required>
<label><b>Surname</b></label>
<input type="text" placeholder="Enter your Surname!" name="surname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<label><b>Email</b></label>
<input type="email" placeholder="Enter Email" name="email" required>
<div class="avatar"><label>Select your avatar: </label>
<input type="file" name="avatar" accept="image/*" required />
<button type="submit" name="reg_user">Register</button>
</div>
<div class="container">
<button type="button" class="cancelbtn" id="cncl2">Cancel</button>
</div>
</form>
</div>
<script src="myscripts.js"></script>
</body>
</html>
user_index.php: is pretty much similar to register.php, it's where people who have registered or logged-in are redirected. I'm posting the beginning of the code.
<?php include('server.php'); ?>
<?phpinclude('auth.php');
session_start();
if ($_SESSION['username']<1) {
session_destroy();
unset($_SESSION['username']);
header("Location: register.php");
}
$db = mysqli_connect('localhost', 'root', '', 'registration');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($db,"SELECT email FROM users WHERE
username='$_SESSION['username']'");
$row = mysqli_fetch_array($result);
$_SESSION['email'] = $result;
$username = $_SESSION['username'];
$_SESSION['id']=$id;
header("Location: server.php");
?>
server.php: contains the validation for registration and logging-in. Also, links to the DB. I will be skipping the validation parts.
<?php
session_start();
$email=$_SESSION['email'];
// initializing variables
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'registration');
//...validationon code
//once no errors, register user
if (count($errors) == 0) {
$password = md5($password);//encrypt the password before saving in the
database
$query = "INSERT INTO users (username, email, password, name, surname)
VALUES('$username', '$email', '$password', '$name', '$surname')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in";
header('Location: user_index.php');
}
}
// LOGIN USER
$msg = '';
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND
password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
session_start();
$_SESSION['email']=$row['email'];
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['id']= $id;
$_SESSION['success'] = "You are now logged in";
header('Location: user_index.php');
}else {
echo $msg;
}
}
}
auth.php
<?php
session_start();
if(!isset($_SESSION["username"])){
echo $errors; }
?>
For any additional information you might need, please feel free to ask anything.
I am genuinely sorry for the block of text and code.

Failing connecting/submitting to MySQL with "PHP form"

I have 2 problems.
Basic story: I have created a SIMPLE registration and login system.
Problem1: If I try to register a new account then it says "user registration failed". At the moment it should say that because mysql can't get right information from forms. But problem is that I don't know why. Everything seems correct...
Problem2: If I try to login with existent account then it seems that browser is only refreshing the page and nothing else...
Registration with php code:
<?php
require ('insert.php');
// If values posted, insert into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$name = $_POST['name'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
// nimi refers to name, it's correct
$query = "INSERT INTO `user` (nimi, email, username, password)
VALUES('$name', '$email', '$username', '$password')";
//POST retrieves the data.
$result = mysqli_query($connection, $query);
if($result){
$smsg = "User Created Successfully.";
} else {
$fmsg = "User Registration Failed";
}
}
mysqli_close($connection);
?>
<html>
...
<body>
...
<div>
<form method="POST" class="form-horizontal" role="form">
<!-- Status, how registering went -->
<?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
<?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
<!-- Registration form starts -->
<h2>Form</h2><br>
<label for="Name"></label>
<input name="name" type="text" id="name" maxlength="40" placeholder="Ees- ja perenimi" class="form-control" autofocus> <!-- lopp -->
<label for="email"></label>
<input name="email" type="email" id="email" maxlength="65" placeholder="Email" class="form-control"> <!-- lopp -->
<label for="Username"></label>
<input name="username" type="text" id="userName" maxlength="12" placeholder="Kasutajatunnus/kasutajanimi" class="form-control" required> <!-- lopp -->
<label for="Password"></label>
<input name="password" type="password" id="password" maxlength="12" placeholder="Parool" class="form-control" required>
<button type="submit" class="btn btn-primary btn-block">Join</button>
</form> <!-- /form -->
</div> <!-- ./container -->
...
</body>
</html>
Login:
<?php
session_start();
require ('insert.php');
//Is username and password typed?
if (isset($_POST['username']) and isset($_POST['password'])){
//Making vars from inputs
$username = $_POST['username'];
$password = $_POST['password'];
//Checking existent of values.
$query = "SELECT * FROM `liikmed`
WHERE username='$username'
and password='$password'";
$result = mysqli_query($connection, $query)
or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
//3.1.2 If values equal, create session.
if ($count == 1){
$_SESSION['username'] = $username;
} else {
//If credentials doesn't match.
$fmsg = "Invalid Login Credentials.";
}
}
//if user logged in, welcome with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hai " . $username . "";
echo "This is the Members Area";
echo "<a href='logout.php'>Logout</a>";
}else{}
?>
<html>
...
<body>
...
<div id="bg"></div>
<form method="POST" class="form-horizontal">
<h2>Login</h2><br>
<label for="User"></label>
<input name="username" type="text" maxlength="15" placeholder="Username" class="form-control" required autofocus>
<label for="Password"></label>
<input name="password" type="password" maxlength="50" placeholder="Password" class="form-control" required autofocus>
<button type="submit" class="btn btn-primary btn-block">Enter</button>
</form>
</div>
...
</body>
</html>
And finally php database connection file (called insert.php):
<?php
$connection=mysqli_connect("localhost","root","pw");
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'my_database');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
?>
First of all in your login PHP code, you only started a session but you didn't tell the from where to direct to if login is successful. Add a header to the code. That is;
if ($count == 1){
$_SESSION['username'] = $username;
header("Location: page.php"); //the page you want it to go to
}
And your registration PHP code looks ok. Check your database table if you've misspelt anything there.
Your logic to set the $_SESSION['username'] requires that the username and password combination exists once in your database.
This might sound silly but can you confirm that this is the case (i.e. confirm that you have not created the same username and password combination).
Altering the logic to be > 1 would also get around this temporarily. So your code
if ($count == 1){
$_SESSION['username'] = $username;
}
should become
if ($count > 1){
$_SESSION['username'] = $username;
}

PHP When i press the login button nothing happen

I was trying to create a login page, but it doesn't seem to work. When I enter details and click login. Nothing happens. I try to login again, still nothing happens. I want to happen is when i login a popup window will appear and i will be directed to the homepage
<?php
$con = mysqli_connect("localhost","root","","onlineshop");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<div class = "boxlog1"
<form method="post" action="" enctype="multipart/form-data">
<input type="text" name="uname" placeholder="Username"class="username" required />
<input type="text" name="lpass" placeholder="Password" class="passwordl" required />
<input type="submit" value="Log In" class="log" name="log"/>
</form>
<p class="forget">Forget password</p>
</div>
<?php
if (isset($_POST['log'])){
$c_email = $_POST['uname'];
$c_pass = $_POST['lpass'];
$sel_c = "select * from customers where customer_pass='$c_pass' AND customer_email='$c_email'";
$run_c = mysqli_query($con, $sel_c);
$check_customer = mysqli_num_rows($run_c);
if($check_customer == 0){
echo "<script>alert('Password or Email is incorrect!')</script>";
exit();
}
else{
$_SESSION['customer_email']=$c_email;
echo "<script>alert('login!')</script>";
echo "<script>window.open('paymnet.php','_self')</script>";
}
}
?>
Add the page to the form action
For example:
<form action"login.php">
Or use
<form action"<?php echo $_SERVER['PHP_SELF']; ?>">
And close your div tag with '>', so
<div class="boxlog1">
Working example
<?php
if (!isset($_SESSION)) { session_start(); }
$con = mysqli_connect("localhost","root","","onlineshop");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<div class="boxlog1">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type="text" name="uname" placeholder="Username"class="username" required />
<input type="text" name="lpass" placeholder="Password" class="passwordl" required />
<input type="submit" value="Log In" class="log" name="log"/>
</form>
<p class="forget">Forget password</p>
</div>
<?php
if (isset($_POST['log'])){
$c_email = $_POST['uname'];
$c_pass = $_POST['lpass'];
$sel_c = "select * from customers where customer_pass='$c_pass' AND customer_email='$c_email'";
$run_c = mysqli_query($con, $sel_c);
$check_customer = mysqli_num_rows($run_c);
if($check_customer == 0){
echo "<script>alert('Password or Email is incorrect!')</script>";
exit();
} else {
$_SESSION['customer_email']=$c_email;
echo "<script>alert('login!')</script>";
echo "<script>window.open('paymnet.php','_self')</script>";
}
}
?>
And here with updated security against SQL Injection. Dont forget to encrypt your password so it cannot be stolen
<?php
if (!isset($_SESSION)) { session_start(); }
$con = mysqli_connect("localhost","root","","onlineshop");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<div class="boxlog1">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type="text" name="uname" placeholder="Username"class="username" required />
<input type="text" name="lpass" placeholder="Password" class="passwordl" required />
<input type="submit" value="Log In" class="log" name="log"/>
</form>
<p class="forget">Forget password</p>
</div>
<?php
if (isset($_POST['log']) && isset($_POST['uname']) && isset($_POST['lpass'])){
$c_email = bin2hex(htmlspecialchars($_POST['uname']));
$c_pass = bin2hex(htmlspecialchars($_POST['lpass']));
$sel_c = "SELECT * FROM customers WHERE customer_pass=UNHEX('$c_pass') AND customer_email=UNHEX('$c_email')";
$run_c = mysqli_query($con, $sel_c);
$check_customer = mysqli_num_rows($run_c);
if($check_customer === 0){
echo "<script>alert('Password or Email is incorrect!')</script>";
exit();
} else {
$_SESSION['customer_email']=$c_email;
echo "<script>alert('login!')</script>";
echo "<script>window.open('paymnet.php','_self')</script>";
}
}
?>
I did'nt changed really much. Just closed your div tag correctly and added an action. However, it does work without the action filled in.

PHP and MySQL Cookie and Header doesn't work

I have a problem and I hope someone will be able to find a solution.
I just changed hoster and the website doesn't work completely.
Basically the problem is that some code doesn't work.
Where it checks if(!empty($db_password) and ($md5pass == $db_password))
The echo works but the other things don't and it's not only there. I have a similar problem with other files as well.
$username = $_POST['user'];
if(isset($username))
{
$password = $_POST['password'];
$md5pass = md5($password);
$check_user = "SELECT ID,username,password FROM Members ";
$check_user .= "WHERE username = '".$username."'";
$checkuser_query = mysqli_query($dbconnection,$check_user);
while($row = mysqli_fetch_array($checkuser_query,MYSQL_ASSOC))
{
$db_userid = $row['ID'];
$db_username = $row['username'];
$db_password = $row['password'];
$db_avatar = $row['avatar'];
}
if(!empty($db_password) and ($md5pass == $db_password))
{
echo 'you are not awesome.';
setcookie("LoginAuthorised","LoginAuthorised",time()+7200,"/");
setcookie("id",$db_userid,time()+7200,"/");
setcookie("username",$db_username,time()+7200,"/");
header("Location: user.php?value=confirm");
}else
{
echo '<div id="error">Password does not match</div>';
}
}
echo '<p></p><p></p>
<div id="lg_login_form">
<form name="login_form" method="post">
<div id="lg_login_title">Log In</div>
<div id="lg_login_form2">
<label>Username:</label>
<input type="text" name="user" id="username" value="" maxlength="20" />
<label>Password:</label>
<input type="password" name="password" value="" maxlength="20" />
<input name="submit_login" type="submit" value="Log In" id="lg_submit_log" />
<p></p>
<p></p>
<div id="lg_control_text">You have to login to access User Panel</div>
</div>
</form>
<form name="register_redirect" action="user.php?value=register" method="post" id="lg_register_redirect" >
<label>If you want to login you have to register first. Registering takes only a few moments and it gives you multiple features.<br/></label>
<input name="submit_registration" type="submit" value="Register" id="lg_submit_reg_log" />
<p></p>
</form>
</div>';
You're sending headers before setcookie() is called, which is probably why you're having issues. Remove the line that says echo 'you are not awesome.';

Categories