i have two page :
login.php :
<form action="conn.php" method="POST">
Username:
<input type="text" id="username" name="username" />
Password:
<input type="password" id="password" name="password" />
<input name="submit" id="submit" type="submit" value="Login" />
</form>
And the PHP
<?php
$success = "";
if(isset($_POST['submit']) == "Login" )
{
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$error = array();
// Username Validation
if(empty($username))
{
$error[] = " Empty or invalid username ";
}
if(empty($password)){
$error[] = "Enter your password";
}
if(count($error) == 0){
$host = 'localhost';
$database_name = 'projett';
$database_user_name = '';
$database_password = '';
$connection=new MongoClient();
if($connection){
// Select Database
$database = $connection->$database_name;
// Select Collection
$collection = $database->reg_users;
$user_data= array("username" => $username,"password" => md5($pass));
$result = $collection->findOne($user_data);
if($result){
$success = "You are successully loggedIn";
header("Location: Articles.php");
}
} else {
die("Mongo DB not installed");
}
}
}
?>
i want display on Member.php the username of the member but when he complete login form a new page open(article.php) with his username
Related
I am not a professional at this, so that being said everything is fairly new to me. I've been researching and trying to figure out my error, but no luck :(. Am I using session_start() wrong? Here is my code:
profile.php This is the page I want it to echo in.
<?php
session_start();
include("connect.php");
include("functions.php");
if(logged_in())
{
?>
<?php
}
else
{
header("location:login.php");
exit();
}?>
<div id='userid'> <?php echo $_SESSION['userid']; ?></div>
login.php
<?php
session_start();
include("connect.php");
include("functions.php");
if(logged_in())
{
header("location:quotin.php");
exit();
}
$error = "";
if(isset($_POST['submit']))
{
$_SESSION['email'] = mysqli_real_escape_string($con, $_POST['email']);
$_SESSION['firstName'] = mysqli_real_escape_string($con, $_POST['fname']);
$_SESSION['lastName'] = mysqli_real_escape_string($con, $_POST['lname']);
$_SESSION['password'] = mysqli_real_escape_string($con, $_POST['password']);
$_SESSION['userid'] = mysqli_real_escape_string($con, $_POST['userid']);
$_SESSION['image'] = mysqli_real_escape_string($con, $_POST['image']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$checkBox = isset($_POST['keep']);
if(email_exists($email,$con))
{
$result = mysqli_query($con, "SELECT password FROM users WHERE email='$email'");
$retrievepassword = mysqli_fetch_assoc($result);
if(!password_verify($password, $retrievepassword['password']))
{
$error = "Password is incorrect";
}
else
{
$_SESSION['email'] = $email;
if($checkBox == "on")
{
setcookie("email",$email, time()+3600);
}
header("location: quotin.php");
}
}
else
{
$error = "Email Does not exists";
}
}?>
<body>
<div id="error" style=" <?php if($error !=""){ ?> display:block; <?php } ?> "><?php echo $error; ?></div>
<div id="wrapper">
<div id="menu">
Sign Up
Login
</div>
<div id="formDiv">
<form method="POST" action="login.php">
<label>Email:</label><br/>
<input type="text" class="inputFields" name="email" required/><br/><br/>
<label>Password:</label><br/>
<input type="password" class="inputFields" name="password" required/><br/><br/>
<input type="checkbox" name="keep" />
<label>Keep me logged in</label><br/><br/>
<input type="submit" name="submit" class="theButtons" value="login" />
</form>
</div>
</div>
</body>
signup.php
<?php
session_start();
include("connect.php");
include("functions.php");
if(logged_in())
{
header("location:profile.php");
exit();
}
$error = "";
if(isset($_POST['submit']))
{ $_SESSION['email'] = mysqli_real_escape_string($con, $_POST['email']);
$_SESSION['firstName'] = mysqli_real_escape_string($con, $_POST['fname']);
$_SESSION['lastName'] = mysqli_real_escape_string($con, $_POST['lname']);
$_SESSION['password'] = mysqli_real_escape_string($con, $_POST['password']);
$_SESSION['userid'] = mysqli_real_escape_string($con, $_POST['userid']);
$firstName = mysqli_real_escape_string($con, $_POST['fname']);
$lastName = mysqli_real_escape_string($con, $_POST['lname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$userid = mysqli_real_escape_string($con, $_POST['userid']);
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$tmp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
$conditions = isset($_POST['conditions']);
$date = date("F, d Y");
if(strlen($firstName) < 3)
{
$error = "First name is too short";
}
else if(strlen($lastName) < 3)
{
$error = "Last name is too short";
}
else if(strlen($userid) > 8)
{
$error = "You need a longer username";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error = "Please enter valid email address";
}
else if(email_exists($email, $con))
{
$error = "Someone is already registered with this email";
}
else if(strlen($password) < 8)
{
$error = "Password must be greater than 8 characters";
}
else if($password !== $passwordConfirm)
{
$error = "Password does not match";
}
else if($image == "")
{
$error = "Please upload your image";
}
else if($imageSize > 1048576)
{
$error = "Image size must be less than 1 mb";
}
else if(!$conditions)
{
$error = "You must be agree with the terms and conditions";
}
else
{
$password = password_hash($password, PASSWORD_DEFAULT);
$imageExt = explode(".", $image);
$imageExtension = $imageExt[1];
if($imageExtension == "PNG" || $imageExtension == "png" || $imageExtension == "JPG" || $imageExtension == "jpg")
{
$image = rand(0, 100000).rand(0, 100000).rand(0, 100000).time().".".$imageExtension;
$insertQuery = "INSERT INTO users(firstName, lastName, userid, email, password, image) VALUES ('$firstName','$lastName','$userid','$email','$password','$image')";
if(mysqli_query($con, $insertQuery))
{
if(move_uploaded_file($tmp_image,"images/$image"))
{
$error = "You are successfully registered";
}
else
{
$error = "Image is not uploaded";
}
}
}
else
{
$error = "File must be an image. PNG or JPG";
}
}
}?>
<body>
<div id="error" style=" <?php if($error !=""){ ?> display:block; <?php } ?> "><?php echo $error; ?></div>
<div id="wrapper">
<div id="menu">
Sign Up
Login
</div>
<div id="formDiv">
<form method="POST" action="signup.php" enctype="multipart/form-data">
<label>First Name:</label><br/>
<input type="text" name="fname" class="inputFields" required/><br/><br/>
<label>Last Name:</label><br/>
<input type="text" name="lname" class="inputFields" required/><br/><br/>
<label>Username:</label><br/>
<input type="text" name="userid" class="inputFields" required/><br/><br/>
<label>Email:</label><br/>
<input type="text" name="email" class="inputFields" required/><br/><br/>
<label>Password:</label><br/>
<input type="password" name="password" class="inputFields" required/><br/><br/>
<label>Re-enter Password:</label><br/>
<input type="password" name="passwordConfirm" class="inputFields" required/><br/><br/>
<label>Image:</label><br/>
<input type="file" name="image" id="imageupload"/><br/><br/>
<input type="checkbox" name="conditions" />
<label>I am agree with terms and conditions</label><br/><br/>
<input type="submit" class="theButtons" name="submit" />
</form>
</div>
</div>
</body>
connect.php I started to use session_start() here.
<?php
$con = mysqli_connect("localhost","root","****","database");
if(mysqli_connect_errno())
{
echo "Error occured while connecting with database ".mysqli_connect_errno();
}?>
functions.php
<?php
function email_exists($email, $con)
{
$result = mysqli_query($con,"SELECT id FROM users WHERE email='$email'");
if(mysqli_num_rows($result) == 1)
{
return true;
}
else
{
return false;
}
}
function logged_in()
{
if(isset($_SESSION['email']) || isset($_COOKIE['email']))
{
return true;
}
else
{
return false;
}
}?>
I'm also not sure why when I sign up, it doesn't register to my database. It did before I started to try and display username, but anymore. Any help is appreciated! Thank you!
The problem is in login.php
$_SESSION['userid'] = mysqli_real_escape_string($con, $_POST['userid']);
You are trying to store the userid in session but there is no POST variable set for it because you are submitting a login page containing only email & password.
And after successful query execution for login you are again storing an email and not the userid in session.
So after successful password comparison first store the userid in the session by retrieving it from db so that session gets a value which you are expecting on profile page.
So try doing:
$result = mysqli_query($con, "SELECT * FROM users WHERE email='$email'"); //Changed the query
$retrievepassword = mysqli_fetch_assoc($result);
if(!password_verify($password, $retrievepassword['password']))
{
$error = "Password is incorrect";
}
else
{
$_SESSION['userid'] = $retrievepassword['userid'];//storing the retrieved userid from db
if($checkBox == "on")
{
setcookie("email",$email, time()+3600);
}
header("location: quotin.php");
}
I am working on a login form and the password doesn't get verified from some reason. The user supposed to log in into system with email and password. I am matching user based on the email with the data in database. Could you please look at it?
Customer table
HTML form in file index.php
<div id="test-popup" class="white-popup mfp-hide col-sm-4 col-sm-offset-4 col-xs-10 col-xs-offset-1 align-center">
<img src="images/logo-white.png" alt="" height="120px" width="120px" />
<h5 class="font-alt">Login to Your Account</h5>
<br/>
<form method="post" action="login.php" class="form">
<div class="mb-20 mb-md-10">
<input type="text" name="email" id="email" class="input-md form-control" placeholder="Email" required />
</div>
<div class="mb-20 mb-md-10">
<input type="password" name="password" id="password" class="input-md form-control" placeholder="Password" required />
</div>
<div class="mb-20 mb-md-10">
<input type="submit" name="login" class="login btn btn-mod btn-medium" id="btnLogIn" value="Login" />
</div>
</form>
</div>
File login.php
<?php
require_once 'connection_db.php';
$response = new stdClass;
if (empty($_POST['email']) || empty($_POST['password'])) {
$response->success = false;
$response->message = 'Email and password cannot be empty.';
} else {
$sql = 'SELECT * FROM `customer` WHERE `email` = ? ';
$email = $_POST['email'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
// print_r($password, true);
try {
$stmt = $db->prepare($sql);
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
$array = $result->fetch_array(MYSQLI_ASSOC);
// print_r($array, true);
if (count($array)) {
$response->success = true;
$response->message = 'Login successful.';
session_start();
$_SESSION['email'] = $email;
$_SESSION['id'] = $id;
$_SESSION['current_page'] = $_SERVER['HTTP_REFERER'];
header("Location: ". $_SESSION['current_page']);
} else {
$response->success = false;
$response->message = 'Wrong username or password.';
header("Location: index.php#test-popup");
}
}
catch (Exception $e) {
$response->success = false;
$response->message = "Error.";
}
}
// unset($db);
?>
Here's a generic setup of how your login script should look:
if (isset($_POST['submit']))
{
$email = $_POST['email'];
$password = $_POST['password'];
if (!empty($email) && !empty($password))
{
$res = $dbh->prepare("SELECT * FROM `customer` WHERE `email` = ?");
$res->execute([$email]);
$row = $res->fetch(MYSQLI_ASSOC);
if ($res->rowCount() > 0)
{
if (password_verify($password, $row['password']))
{
$_SESSION['user_session'] = $row['uid'];
header('Location: loggedIn.php');
} else {
// echo incorrect pass
}
} else {
// echo no such user...
}
} else {
// echo something...
}
}
You should be using password_verify for your login script. You only use password_hash for registering to hash the password that has been submitted.
I want to make a login form when a person has just completed in another form for registration. Now i have this code, and when i finish to complete. I have no message, I think my code is incomplete. Thanks
<form action="conn.php" method="POST">
Username:
<input type="text" id="username" name="username" />
Password:
<input type="password" id="password" name="password" />
<input name="submit" id="submit" type="submit" value="Login" />
</form>
<?php
$success = "";
if(isset($_POST['submit']) == "Login" )
{
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$error = array();
// Username Validation
if(empty($username))
{
$error[] = " Empty or invalid username ";
}
if(empty($password)){
$error[] = "Enter your password";
}
if(count($error) == 0){
$host = 'localhost';
$database_name = 'projett';
$database_user_name = '';
$database_password = '';
$connection=new MongoClient();
if($connection){
// Select Database
$database = $connection->$database_name;
// Select Collection
$collection = $database->reg_users;
$user_data= array("username" => $username,"password" => md5($pass));
$result = $collection->findOne($user_data);
if($result){
$success = "You are successully loggedIn";
header("Location: Articles.php");
}
} else {
die("Mongo DB not installed");
}
}
}
?>
php code of registration :
if(isset($_POST['submit'])){
//getting post variable
$email=strip_tags($_POST['email']);
$pass=strip_tags($_POST['password']);
$confirm_pass=strip_tags($_POST['confirm_password']);
$username=strip_tags($_POST['username']);
$error = array();
if(empty($email) or !filter_var($email,FILTER_SANITIZE_EMAIL))
{
$error[] = " <h2> complete email </h2>";
}
if(empty($username)){
$error[] = " <h2> complete username ! </h2>";
}
if(empty($pass)){
$error[] = " <h2> complete your password </h2> ";
}
if(empty($confirm_pass)){
$error[] = " <h2> confirm password </h2> ";
}
if($pass != $confirm_pass){
$error[] = " <h2> password not same </h2> ";
}
if(count($error) ==0){
//database configuration
$host = 'localhost';
$database_name = 'projett';
$database_user_name = '';
$database_password = '';
//if you have database user name & password then connection may be
//$connection=new Mongo("mongodb://$database_user_name:$database_password#$dbhost");
//Currently we are connecting to mongodb without authentication
$connection=new MongoClient();
//checking the mongo database connection
if($connection){
//connection database
$databse=$connection->$database_name;
//connection à la collection reg_user
$collection=$databse->reg_users;
$query=array('username'=>$username);
//checking for existing user
$count=$collection->findOne($query);
if(!count($count)){
//Save the New user
$user_data=array('email'=>$email,'password'=>md5($pass),'username'=>$username);
$collection->save($user_data);
echo " <h2> Vous êtes inscrit avec succès ! </h2> ";
}else{
echo " <h2> Username already exists </h2> ";
}
}else{
die(" <h2> Database are not connected </h2>" );
}
}else{
//Displaying the error
foreach($error as $err){
echo $err.'<br />';
}
}
}
This may cause a problem: isset($_POST['submit']) == "Login"
You're trying to do two things here. The function isset() returns TRUE or FALSE. So you're comparing that boolean value to the string "Login".
It should be either this: isset($_POST['submit'])
or this: $_POST['submit'] == "Login"
but not both.
TRUE/FALSE will never equal "Login"
I have already created a successfull login form that is connected to a database to determine whether or not a login is correct. But i would like to update this so that if an incorrect username or password is entered they will get an error message. Im just not to sure how to implement that into my existing code?...
my user login page:
<form action="../login.php" method="post">
<label for="login-username"><i class="icon-user"></i> <b>Username</b> </label><br/>
<input class="form-control" type="text" name="username">
<br/>
<label for="login-password"><i class="icon-lock"></i> <b>Password</b> </label> <br/>
<input class="form-control" type="password" name="password">
<br/>
<button type="submit" class="btn pull-right">Login</button>
</form>
<?php
if (isset($_SESSION['username'])){
if($_SESSION['logged_in'] = 1){
echo ('Logged in as: '. $_SESSION['username'].' '.$_SESSION['surname']).'<br>Log out';
}
}
?>
and the login.php it is posting to:
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gpdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
//echo "connection successful";
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM patients where Username ='$username' and Password ='$password'";
$result = $conn->query($sql);
$admin_user = 'admin';
$admin_password = 'admin1';
if ($result->num_rows > 0) {
if ($username === $admin_user || $password === $admin_password ){
foreach($result as $row) {
//echo "PatientID " .$row["PatientID"]."<br>". "First name and Last name: " . $row["Firstname"]. " ".$row["Surname"]. "<br/>";
$_SESSION['id'] = $row["PatientID"];
$_SESSION['username'] = $row["Firstname"];
$_SESSION['surname'] = $row["Surname"];
$_SESSION['logged_in'] = 2;
header("location: http://localhost/index.php");
die;
}
}else{
foreach($result as $row) {
$_SESSION['id'] = $row["PatientID"];
$_SESSION['username'] = $row["Firstname"];
$_SESSION['surname'] = $row["Surname"];
$_SESSION['logged_in'] = 1;
header("location: http://localhost/index.php");
die;
}
}
}else{
$_SESSION['logged_in'] = 0;
header("location: http://localhost/user.php");
die;
}
?>
<?php
if ($result->num_rows > 0){
header("location: http://localhost/index.php");
}else{
echo "Wrong Username or Password <br />".
'Go back...';
}
?>
You may also create a login_failure.php page and in the else part redirect the user to that page. OR another approach is to pass the value of failure message
header("location: http://localhost/user.php?msg = 1");
and display the message at the top of login box. Get the value of 'msg' in user.php page and apply if condition to display the message.
<div><?php
$msg = $_GET['msg'];
if (isset($msg)) { echo "Wrong username/password"; } ?> </div>
<form action="../login.php" method="post">
<label for="login-username"><i class="icon-user"></i> <b>Username</b> </label><br/>
<input class="form-control" type="text" name="username">
<br/>
<label for="login-password"><i class="icon-lock"></i> <b>Password</b> </label> <br/>
<input class="form-control" type="password" name="password">
<br/>
<button type="submit" class="btn pull-right">Login</button>
</form>
I'm developing a user registration and login for a an app using jQuery and PHP. I am having trouble inserting a record into my members database. When I click submit I'm getting the "Not Registered" alert., it just takes me back to the registration page.
My jQuery handle for the submit button and the HTML:
$('#regsubmit').click(function(){
$.post("register.php",{reguser: $("#reguser").val(), fname: $("#fname").val(),lname: $("#lname").val(),regpass: $("#regpass").val(), regemail: $("#regemail").val()},function(data){
if(data == true){
alert("Registered");
}else{
alert("Not Registered");
}
});
});
<div data-role="content">
<div data-role="collapsible"><h2>Register</h2>
<form action="" method="post" id="registrationform">
<div data-role="fieldcontain">
<label for="fname">First name:</label>
<input type="text" name="fname" id="fname" value="" />
<div id="fnamecheck"></div>
</div>
<div data-role="fieldcontain">
<label for="lname">Last name:</label>
<input type="text" name="lname" id="lname" value="" />
<div id="lnamecheck"></div>
</div>
<div data-role="fieldcontain">
<label for="regemail">Email:</label>
<input type="email" name="regemail" id="regemail" value="" />
<div id="emailcheck"></div>
</div>
<div data-role="fieldcontain">
<label for="reguser">Username:</label>
<input type="text" name="reguser" id="reguser" value="" />
<div id="usernamecheck"></div>
</div>
<div data-role="fieldcontain">
<label for="regpass">Password:</label>
<input name="regpass" type="password" id="regpass" value="">
<div data-role="fieldcontain"><label for="confirmregpass">Confirm Password:</label>
<input name="confirmregpass" type="password" id="confirmregpass" value=""></div>
</div>
<input name="regsubmit" type="submit" id="regsubmit" value="Register" data-icon="check" data-theme="a"/>
</form>
</div>
And my register.php:
<?php
$MYSQL_SERVER = "localhost";
$MYSQL_USER = "root";
$MYSQL_PASSWORD = "password";
$db = mysql_connect($MYSQL_SERVER, $MYSQL_USER, $MYSQL_PASSWORD ) or die(mysql_error());
mysql_select_db("hedonsof_conflict") or die(mysql_error());
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['regemail'];
$reguser = $_POST['reguser'];
$regpass = $_POST['regpass'];
//Username check
$usercheck = mysql_query("SELECT * FROM members WHERE username='".$reguser."'");
if(empty($fname)||empty($lname)||empty($email)||empty($reguser)||empty($regpass)){
if(empty($fname)){
$errors[] = "Missing first name.";
}
if(empty($lname)){
$errors[]= "Missing last name.";
}
if(empty($email)){
$errors[]= "Missing email.";
}
if(empty($reguser)){
$errors[]= "Missing user name.";
}
if(empty($regpass)){
$errors[] = "Missing password.";
}
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors = "Not a valid eail address.";
}else{
$fname = strip_tags($fname);
$fname = stripslashes($fname);
$fname = trim($fname);
$lname = strip_tags($lname);
$lname = stripslashes($lname);
$lname = trim($lname);
$email = strip_tags($email);
$email = stripslashes($email);
$email = trim($email);
$reguser = strip_tags($reguser);
$reguser = stripslashes($reguser);
$reguser = trim($reguser);
$regpass = strip_tags($regpass);
$regpass = stripslashes($regpass);
$regpass = trim($regpass);
$sql = mysql_query("INSERT INTO members (username, fname, lname, password, email) VALUES('$reguser','$fname','$lname','$regpass','$email)") or die(mysql_error());
$msg = "Thanks for Registering.";
if($msg){
echo true;
}else{
$errors[] = "Sorry error with database at this time.";
echo $errors;
}
}
?>
EDIT:
<?php
$MYSQL_SERVER = "localhost";
$MYSQL_USER = "root";
$MYSQL_PASSWORD = "password";
$db = mysql_connect($MYSQL_SERVER, $MYSQL_USER, $MYSQL_PASSWORD ) or die(mysql_error());
mysql_select_db("hedonsof_conflict") or die(mysql_error());
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['regemail'];
$reguser = $_POST['reguser'];
$regpass = $_POST['regpass'];
$errors[] = "";
//Username check
$usercheck = mysql_query("SELECT * FROM members WHERE username='".$reguser."'");
if(empty($fname)){
$errors[] = "Missing first name.";
}
if(empty($lname)){
$errors[]= "Missing last name.";
}
if(empty($email)){
$errors[]= "Missing email.";
}
if(empty($reguser)){
$errors[]= "Missing user name.";
}
if(empty($regpass)){
$errors[] = "Missing password.";
}
// }elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
// $errors = "Not a valid email address.";
else{
$fname = strip_tags($fname);
$fname = stripslashes($fname);
$fname = trim($fname);
//$fname = mysqli_real_escape_string($fname);
$lname = strip_tags($lname);
$lname = stripslashes($lname);
$lname = trim($lname);
//$lname = mysqli_real_escape_string($lname);
$email = strip_tags($email);
$email = stripslashes($email);
$email = trim($email);
//$email = mysqli_real_escape_string($email);
$reguser = strip_tags($reguser);
$reguser = stripslashes($reguser);
$reguser = trim($reguser);
//$reguser = mysqli_real_escape_string($reguser);
$regpass = strip_tags($regpass);
$regpass = stripslashes($regpass);
$regpass = trim($regpass);
//$regpass = mysqli_real_escape_string($regpass);
$sql = mysql_query("INSERT INTO members (username, fname, lname, password, email) VALUES('$reguser','$fname','$lname','$regpass','$email')") or die(mysql_error());
$msg = "Thanks for Registering.";
if($msg){
echo "true";
}else{
$errors[] = "Sorry error with database at this time.";
echo "false";
}
}
?>
Try this:
$('#regsubmit').click(function(e){
e.preventDefault();
$.post("register.php",{reguser: $("#reguser").val(), fname: $("#fname").val(),lname: $("#lname").val(),regpass: $("#regpass").val(), regemail: $("#regemail").val()},function(data){
if(data == true){
alert("Registered");
}else{
alert("Not Registered");
}
});
return false;
});