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;
}
Related
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.
Good day.
So below i have a php script that is supposed to query my db and look for user details. the db is set up and the data is available in it. the issue here seems that once i click the submit button with my user entered details, it fails on the first if statement, to see if the email exists. i am not sure why.
But here is the submit form.
<form action = "submit2.php" method="Post" >
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="email">Email</label> -->
<input type="text" id="email" name="email" class="form-control" placeholder="Your user name">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="subject">Subject</label> -->
<input type="text" id="password" name="password" class="form-control" placeholder="Your Password">
</div>
</div>
<div class="form-group">
<input type="submit" value="Login" class="btn btn-primary">
</div></form>
and here is the submit2.php that is supposed to manipulate the data from the form and query the db.
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$useremail = mysqli_real_escape_string($connection,$_POST['email']);
$userpassword = mysqli_real_escape_string($connection, $_POST['password']);
if (empty($useremail) || empty($userpassword)){
header("Location: customerportal.php?login=empty");
exit();
}
else{
$sql = "SELECT * FROM 'USERS' where EMAIL ='$useremail';";
$emailresult = mysqli_query($connection, $sql);
$emailresultcheck = mysqli_num_rows($emailresult);
//check if email exists
if($emailresultcheck == 0){
header("Location: customerportal.php?login=invalidEmail");
}
else {
if($row = mysqli_fetch_assoc($emailresult)){
//dehash the password
$hashedPWDCheck = password_verify($userpassword,$row['ENCRYPTEDPWD']);
if($hashedPWDCheck == false){
header("Location: customerportal.php?login=passwordincorrect");
exit();
}
elseif($hashedPWDCheck == true){
$_SESSION['email'] = $email;
// header("Location: Landingpage.php");
echo "Success";
}
}
else{
header("Location: customerportal.php?login=invalid");
exit();
}
}
}
}
?>
The submit always fails else statement and returns the invalidEmail header location and i am not sure why. the Connection file is below.what am i missing?
<?php
$connection = mysqli_connect("localhost", "root", "");
if(!$connection){
echo "Failed to connect database" . die(mysqli_error($connection));;
}
$dbselect = mysqli_select_db($connection, "dhctest");
if(!$dbselect){
echo "Failed to Select database" . die(mysqli_error($connection));
}
?>
Change this
$sql = "SELECT * FROM 'USERS' where EMAIL = '$useremail';";
to this
$sql = "select * from users where email = $useremail";
Okay, so solved the issue, by running a var_dump() on everyone of my variables until i came across the error that was being outputted by my sql code.
On the line
$sql = "SELECT * FROM 'USERS' where EMAIL = '$useremail';";
I had to remove the '' and replace with ``.
And that seems to have solved the issue.
Thank you for everyone who assisted.
I've created a login/registration system and the registration part is working fine. However, now I am trying to login and when you login it should start a session and redirect you to account.php page but it's not doing that. It's just refreshing the page and doing nothing else.
Index page:
<?php
include 'dbh.php';
session_start();
if(isset($_SESSION['id'])){
$result = $conn->query("SELECT * FROM users where id=".$_SESSION['id']);
$row = $result->fetch_array(MYSQLI_BOTH);
}
# REGISTRATION HANDLER
if(isset($_POST['rsubmit'])){
$username = $_POST['username'];
$email = $_POST['email'];
$plainpass = $_POST['password'];
$password = password_hash($plainpass, PASSWORD_BCRYPT, array('cost' => 10));
$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($conn, $sql);
$btn = "Account created! Please login";
}else {
$btn = "Register";
}
# LOGIN HANDLER
if(isset($_POST['lsubmit'])){
$lemail = $_POST['lemail'];
$lpassword = $_POST['lpassword'];
$result = $conn->query("SELECT * FROM users where email='$lemail'");
$row = $result->fetch_array(MYSQLI_BOTH);
if(password_verify($lpassword, $row['password'])){
$_SESSION['id'] = $row['id'];
Header("Location: account.php");
}
} else {
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>Liam4Life</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form" action="index.php" method="POST">
<input required name="username" type="text" placeholder="Username"/>
<input required name="rpassword" type="password" placeholder="Password"/>
<input required name="remail" type="email" placeholder="Email address"/>
<button>Register</button>
<p class="message">Already registered? Sign In</p>
</form>
<form class="login-form" action="index.php" method="POST">
<input required name="lemail" type="email" placeholder="Email"/>
<input required name="lpassword" type="password" placeholder="Password"/>
<button type="submit" name="lsubmit">Login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
DBH.php:
<?php
$conn = mysqli_connect("localhost", "root", "", "game");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
if(isset($_SESSION['id'])){
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
$_SESSION['password'] = $row['password'];
}
?>
Instead of Header("Location: account.php");
use the following statement
echo "<script>location.href='account.php'</script>";exit;
The issue as mentioned by Jeff, it can be due to space the redirection is not happening. If the above logic works. Then remove additional space in config / else need to add session_start() as the first line of statement in your index.php file and have the header("Location: account.php") logic.
Note: To debug, ensure the control goes here by printing and adding a exit statement.
try
Index page:
<?php
session_start();
include 'dbh.php';
-----code---------
?>
DBH.php:
<?php
session_start();
-----code---------
?>
//session_start(); needed to give top of page and here it is missing in DBH.php. Hence $_SESSION not working
Try next approach:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "game");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
if(!empty($_SESSION['id'])){
$result = $conn->query("SELECT * FROM users where id=".(int)$_SESSION['id']);
if(!$result->num_rows) {
session_destroy();
Header("Refresh:0");
exit;
}
Header("Location: account.php");
exit;
}
# LOGIN HANDLER
if(isset($_POST['lsubmit']) && !empty($_POST['lemail'])){
$lemail = mysqli_real_escape_string($_POST['lemail']);
$result = $conn->query("SELECT * FROM users where email='{$lemail}'");
$row = $result->fetch_array(MYSQLI_BOTH);
if(password_verify($_POST['lpassword'], $row['password'])){
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
$_SESSION['password'] = $row['password'];
Header("Location: account.php");
exit;
}
}
# REGISTRATION HANDLER
elseif(isset($_POST['rsubmit']) && !empty($_POST['email'])){
$username = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = password_hash($_POST['password'], PASSWORD_BCRYPT, array('cost' => 10));
$result = $conn->query("INSERT INTO users (username, email, password) VALUES ('{$username}', '{$email}', '{$password}')");
$btn = "Account created! Please login";
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>Liam4Life</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form" action="index.php" method="POST">
<input required name="username" type="text" placeholder="Username"/>
<input required name="rpassword" type="password" placeholder="Password"/>
<input required name="remail" type="email" placeholder="Email address"/>
<button>Register</button>
<p class="message">Already registered? Sign In</p>
</form>
<form class="login-form" action="index.php" method="POST">
<input required name="lemail" type="email" placeholder="Email"/>
<input required name="lpassword" type="password" placeholder="Password"/>
<button type="submit" name="lsubmit">Login</button>
<p class="message">Not registered? Create an account</p>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
its my first time creating a login page.
I want users to login, then the page redirects to the customer account page, if they have a account. I have added echo's so i can see whats happening. I have a "Logged in successfully" alert that works perfectly when i login. The page just does not redirect.
HTML
<section class="container">
<form id="myform " class="Form" method="post" action="login.php" accept-charset="utf-8">
<!-- <div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value='' required>
<input class ="login-field" type="password" id="pass1" name="pass1" value="" placeholder="Password" maxlength="30" required>
<input type="submit" name="login" value="login" class="btn ">
<br>
</form>
PHP
<?php
session_start();
require ('./mysql.inc.php');
?>
<?php
if (isset($_POST['login']))
//database varianbles
$c_email = $_POST['email'];
$c_password = $_POST['pass1'];
// select login details
$sel_c = "SELECT * FROM Cus_Register WHERE Cus_Email='$c_email' AND Cus_Password='$c_password'";
$run_c = mysqli_query($dbc, $sel_c);
//check if customer is on databse
$check_customer = mysqli_num_rows($run_c);
if ($check_customer == 0) {
echo "<script> alert('password or email is incorrect please try again')</script>";
exit();
}
else{
$_SESSION['Cus_Email'] = $c_email;
echo "<script> alert ('Logged in successfully')</script>";
echo "<script>window.open('./customer/Cus_Account.php'.'_self') </script>";
}
?>
You may use header() to redirect
else
{
$_SESSION['Cus_Email'] = $c_email;
header('Location: customer/Cus_Account.php');
exit();
}
hope it helps:)
Do you intend window.open('./customer/Cus_Account.php'.'_self') to be window.open('./customer/Cus_Account.php', '_self')?
window.open takes a location and a target parameter and in JavaScript parameters are separated by a comma, not a full stop. In this case './customer/Cus_Account.php' is the location and '_self' is the target.
I am wondering where is the errors that I am missing.
my form would be like this
<form id="myForm" action="loginAction" name="login" method="POST">
<p> <label class="inputField" > Email Address : </label> </p>
<p> <input class="registerField" id="emailid" name="email" required="required" type="text" placeholder="eg. john.wick#yahoo.com"/> <span class="warning" id="emailWarning"> </p>
<p> <label class="inputField" > Password : </label> </p>
<p> <input class="registerField" id="textpwd" name="password" required="required" type="password" placeholder="Your password"/> </p>
<p> <input name="submit" class="registerButton" type="submit" value="LOGIN"> </p>
loginAction.php at the following code below
<?php
// Report all PHP errors
error_reporting(-1);
session_start();
include 'dbconnect.php';
$username = $_POST['email'];
$password = $_POST['password'];
$username = mysqli_real_escape_string(stripslashes($username));
$password = mysqli_real_escape_string(stripslashes($password));
$loginUser = " SELECT registerPassword, emailAddress FROM register_user
WHERE emailAddress = '$username' AND registerPassword = '$password'";
$loginSuccess = mysqli_query($mysqli, $loginUser) or die(mysqli_error($mysqli));
$loginRow = mysqli_num_rows($loginSuccess);
if($loginRow == 1) {
// $_SESSION['login_user'] = $username;
echo "SUCCESSFUL LOGIN";
//header ("Location: index");
} else {
echo "YOU WRONG";
}
mysqli_close($mysqli);
?>
The answer is YOU WRONG even though the password and email are the same. I am aware that I haven't finished session yet, but this can't login, so i cant do further to Session.
you form field name is email not username change
$username = $_POST['username'];
to
$username = $_POST['email'];
Also on error reporting and
remove spaces before opening php tag like <?php session_start();
You put $username = $_POST['username']; in loginAction.php
change it to $username = $_POST['email'];
Because in your form you write:
<input id="emailid" name="email" type="text"/>
and
if($loginRow!=0) {
// $_SESSION['login_user'] = $username;
echo "SUCCESSFUL LOGIN";
//header ("Location: index");
} else {
echo "YOU WRONG";
}