I'm learning PHP. I'm trying to build a website that stores a pdf alongside the $_SESSION's stored email. But everything I try results in "undefined array key error". Here's the main code:
The registration form:
<form action="insert.php" method="post">
<div class="container" style="margin-left: 30%; margin-top: 15%">
<div class="card align-content-center" style="width: 50%; padding-left: 13%">
<div class="form-row mb-2"></div>
<div class="form-row mb-2"> <!-- migliore gestione form php -->
<div class="col-2">
<label for="firstName">Nome:</label>
</div>
<div class="col-3">
<input type="text" name="first_name" id="firstName" required>
</div>
</div>
<div class="form-row mb-2">
<div class="col-2">
<label for="email">Email:</label>
</div>
<div class="col-3">
<input type="email" name="email" id="email" required>
</div>
</div>
<div class="form-row mb-2">
<div class="col-2">
<label for="Password">Password:</label>
</div>
<div class="col-3">
<input type="password" name="password" id="Password" required>
</div>
</div>
<div class="form-row mb-2">
<div class="col-2 offset-4">
<input type="submit" value="Invia" class="btn btn-outline-primary" onclick="return verifica();"> <!-- parte con return true, se false non prosegue -->
</div>
</div>
</div>
</div>
</form>
Pretty basic, nothing special here.
It connects to the "insert.php" page which stores the data.
<?php
include('conn.inc');
$first_name = $_REQUEST['first_name'];
$email = $_REQUEST['email'];
$password = password_hash($_REQUEST['password'], PASSWORD_DEFAULT);
// nome table: ListaUtenti
$sql = "INSERT INTO ListaUtenti (first_name, email, password) VALUES ('$first_name','$email','$password')";
if(mysqli_query($conn, $sql)){
echo "<h3>Dati immagazzinati correttamente in SQL.</h3>";
echo nl2br("\n$first_name\n $email\n $password");
} else{
echo "ERRORE: Qualcosa non è andato come doveva."
. mysqli_error($conn);
}
// Chiudi connessione
mysqli_close($conn);
?>
The login:
<?php
$_SESSION['connesso'] = false;
if (isset($_POST['username']) && isset($_POST['password'])) {
$first_name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
// echo "$password<br>";
// Get username and password from form
// Check if username and password match a record in the database
$result = mysqli_query($conn, "SELECT * FROM listautenti WHERE first_name = '$first_name' AND password = '$password'");
if (mysqli_num_rows($result) == 1) {
// Store the username in the session to indicate that the user is logged in
$_SESSION['username'] = $first_name;
$_SESSION['connesso'] = true;
header("Location: index.php");
exit;
} else {
$error = "Nome o password errati.";
}
}
?>
And now the storing part in the index page. Everything works except the email.
<?php
$message = "File caricato correttamente.";
if(isset($_POST['email'])){
$_SESSION['email'] = $_POST['email'];
}
#connection string
if (isset($_POST["submit"])) {
if (is_uploaded_file($_FILES["file"]["tmp_name"]) && ($_FILES["file"]["type"] == 'application/pdf')) {
echo "";
#file name ha un numero casuale, in modo che non verrà rimpiazzato
$pname = rand(1000, 10000) . "-" . $_FILES["file"]["name"];
#nome temporaneo per immagazzinare il file
$tname = $_FILES["file"]["tmp_name"];
#path per l'upload
$uploads_dir = 'img';
#spostare l'upload in una directory specifica
move_uploaded_file($tname, $uploads_dir . '/' . $pname);
#sql query per inserire in un databse
// $sql = "INSERT into fileup(pdf) VALUES('$pname')";"INSERT into fileup(email) VALUES('email')";
$sql = "INSERT into fileup(pdf, email) VALUES('$pname', '".$_SESSION['email']."')";
if (mysqli_query($conn, $sql)) {
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
echo "Errore.";
}
} else {
echo "Il file è di tipo errato.";
}
}
Thanks in advance, I just don't get why it wouldn't store the email.
EDIT: nevermind, solved! I just added to the login part:
$row = mysqli_fetch_assoc($result);
$_SESSION['email'] = $row['email'];
```
Your login.php and index.php code is lacking session_start(); that will initialize the session for you.
2.) You did not set email variable to session. something like $_SESSION['email'] = $email;
3.) Your Code is also vulnerable to SQL Injection Attack. You should better use prepared statement or PDO
4.) Your Code is vulnerable to session hijacking and Session fixation attack.you will have to regenerate session on login. something like session_regenerate_id();
login.php
<?php
//initialize sessions
session_start();
$_SESSION['connesso'] = false;
if (isset($_POST['username']) && isset($_POST['password'])) {
$first_name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
// echo "$password<br>";
// Get username and password from form
// Check if username and password match a record in the database
$sql = "SELECT * FROM listautenti WHERE first_name=? and password=?"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $first_name,$password);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
//$user = $result->fetch_assoc(); // get data
/*
while ($row = $result->fetch_assoc()) {
$row['first_name'];
}
*/
if (mysqli_num_rows($result) == 1) {
//stop session hijacking and Session fixation attack.
session_regenerate_id();
// Store the username in the session to indicate that the user is logged in
$_SESSION['username'] = $first_name;
$_SESSION['email'] = $email;
$_SESSION['connesso'] = true;
header("Location: index.php");
exit;
} else {
$error = "Nome o password errati.";
}
}
?>
index.php should look like
<?php
//initialize sessions
session_start();
$message = "File caricato correttamente.";
echo $email= $_SESSION['email'];
/*
if(isset($_POST['email'])){
$_SESSION['email'] = $_POST['email'];
}
*/
#connection string
if (isset($_POST["submit"])) {
if (is_uploaded_file($_FILES["file"]["tmp_name"]) && ($_FILES["file"]["type"] == 'application/pdf')) {
echo "";
#file name ha un numero casuale, in modo che non verrà rimpiazzato
$pname = rand(1000, 10000) . "-" . $_FILES["file"]["name"];
#nome temporaneo per immagazzinare il file
$tname = $_FILES["file"]["tmp_name"];
#path per l'upload
$uploads_dir = 'img';
#spostare l'upload in una directory specifica
move_uploaded_file($tname, $uploads_dir . '/' . $pname);
#sql query per inserire in un databse
$sql = $conn->prepare("INSERT INTO fileup (pdf, email) VALUES (?, ?)");
$sql->bind_param("ss", $pname, $email);
if ($sql) {
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
echo "Errore.";
}
} else {
echo "Il file è di tipo errato.";
}
//$sql->close();
//$conn->close();
}
Try it and let me know
Related
I want to show the name of the user after logging in (e.g. Hey User!) using PHP, i tried the $username = $_SESSION['username']; but it keeps giving me nothing (Hey !).
Here's my PHP code:
<?php
session_start();
$connection = mysqli_connect('localhost','root','admin');
mysqli_select_db($connection, 'user_registration');
$email = $_POST['email'];
$password = $_POST['password'];
$verify_emailpass = " select * from user_table where email = '$email' && password = '$password'";
$result = mysqli_query($connection, $verify_emailpass);
$num = mysqli_num_rows($result);
if($num == 1){
$_SESSION['loggedin'] = true;
$username = $_SESSION['username'];
echo "Hey $username !";
}else{
echo "<b>Incorrect Email or Password.</b>";
}
?>
Here's the Html log in From:
<form action="validation.php" method="post">
<div class="row content">
<div class="col-12">
<b><p class="text-align">Se connecter:</p></b>
</div>
<div class="col-12">
<input name="email" type="text" class="input-box shadow-sm" placeholder="Adresse E-mail" required/>
</div>
<div class="col-12">
<input name="password" type="password" class="input-box shadow-sm" placeholder="Mot de passe" required/>
</div>
</div>
<div class="button-2">
<button id="loginButton" type="submit" class="next-button shadow-sm"><img src="res/icons/button-arrow.svg" width="45px" height="45px" /></button>
</div>
</form>
And I was wondering how can i get any information i want from the user after he logs in in order to place it in other pages like Profile page or so?
If this page is login than session is empty
I think it's check mysql email and password
Than this code
$data['username'] username is mysql name column name
<?php
session_start();
$connection = mysqli_connect('localhost','root','admin');
mysqli_select_db($connection, 'user_registration');
$email = $_POST['email'];
$password = $_POST['password'];
$verify_emailpass = " select * from user_table where email = '$email' && password = '$password'";
$result = mysqli_query($connection, $verify_emailpass);
$num = mysqli_num_rows($result);
if($num == 1){
$data = $result->fetch_assoc()
$_SESSION['username'] = $data['username'];
$_SESSION['loggedin'] = true;
$username = $_SESSION['username'];
echo "Hey $username !";
}else{
echo "<b>Incorrect Email or Password.</b>";
}
?>```
Update this line with
$username = $_SESSION['username'];
With this
$username = $result[‘username’]; $_SESSION['username'] =
$username;
I have login form with username and password.If i am entering wrong username or password it is showing blank page not displaying any error messages.it just showing in URL as website.com/Admin/#. Here is the code which i have written:
<form action="#" method="post" role="form" enctype="multipart/form-data">
<?php if ( $msg != '' ) { ?>
<div class="alert alert-success">
<?php echo $msg; ?>
</div>
<?php } ?>
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="field-label">Email</div>
<input type="text" placeholder="User Name" id="username" name="user_name" required>
</div>
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="field-label">Password</div>
<input type="password" placeholder="Password" id="password" name="password" required>
</div>
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="button-box">
<input type="submit" name="submit_login" value="Sign In" class="theme-btn btn-style-one">
</div>
</form>
PHP Code:
<?php
session_start();
include 'db.php';
if ( isset( $_POST['submit_login'] ) ) {
if ( !empty( $_POST['user_name'] ) && !empty( $_POST['password'] ) ) {
$get_user_name = mysqli_real_escape_string( $conn, $_POST['user_name'] );
$get_password = mysqli_real_escape_string( $conn, $_POST['password'] );
// Encrypting the password from text//
$get_password = md5( $get_password );
$sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password'";
if ( $result = mysqli_query( $conn, $sql ) ) {
while ( $rows = mysqli_fetch_assoc( $result ) ) {
if ( mysqli_num_rows( $result ) == 1 ) {
$_SESSION['user'] = $get_user_name;
$_SESSION['password'] = $get_password;
$_SESSION['user_role'] = $rows['user_role'];
if ( $_SESSION['user_role'] === 'admin' ) {
header( 'Location:property-list.php' );
}
} else {
$msg = 'User name or Password was Wrong!';
$msgclass = 'bg-danger';
}
}
} else {
$msg = 'There is somekind of Database Issue!';
$msgclass = 'bg-danger';
}
} else {
$msg = 'User name or Password was empty!';
$msgclass = 'bg-danger';
}
} else {
}
?>
If i give correct username and password its working fine their was no issue in that the only problem is with if i enter wrong username or password or else submitting directly without giving any data it is not displaying message
You need to echo the $msg all the time remove the if in the form then declare mgs and msgclass before the submit action then just echo
<?php
session_start();
include 'db.php';
$msg =""; // declare message
$msgclass =""; //classs
if(isset($_POST['submit_login'])){
if(!empty($_POST['user_name']) && !empty($_POST['password'])){
$get_user_name = mysqli_real_escape_string($conn,$_POST['user_name']);
$get_password = mysqli_real_escape_string($conn,$_POST['password']);
// Encrypting the password from text//
$get_password=md5($get_password);
$sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password'" ;
if($result = mysqli_query($conn,$sql)){
while($rows = mysqli_fetch_assoc($result)){
if(mysqli_num_rows($result) == 1){
$_SESSION['user'] = $get_user_name;
$_SESSION['password'] = $get_password;
$_SESSION['user_role'] = $rows['user_role'];
if($_SESSION['user_role'] === 'admin'){
header('Location:property-list.php');
}
}
else{
$msg = 'User name or Password was Wrong!';
$msgclass='bg-danger';
}
}
}
else {
$msg = 'There is somekind of Database Issue!';
$msgclass='bg-danger';
}
} else {
$msg = 'User name or Password was empty!';
$msgclass='bg-danger';
}
}else {
}
?>
Then
<form action="#" method="post" role="form" enctype="multipart/form-data">
<div class="alert <?php echo $msgclass;?>">
<?php echo $msg;?>
</div>
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="field-label">Email</div>
<input type="text" placeholder="User Name" id="username" name="user_name" required>
</div>
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="field-label">Password</div>
<input type="password" placeholder="Password" id="password" name="password" required>
</div>
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="button-box">
<input type="submit" name="submit_login" value="Sign In" class="theme-btn btn-style-one">
</div>
</form>
NB : You should use prepared statements to prevent sql injections.
Never use md5() as means of password encrption rather use
password_hash() and password_verify()
First you need to target your php file in the action attribute of your form
action="/path/tofile.php"
Most user friendly validation is done with javascript, so the page doesn't have to reload,
but if you really want to use PHP, one way to do it is with sessions.
You can add the $msg and $msgclass to the session variable:
$_SESSSION['response'] = ['message' => $msg, 'class' => $msgclass];
After that use header function to redirect back to your html:
header('Location: /pathtoformfile');
exit;
Note: be careful not to echo or print anything in the script before header.
Finally, in the form file do this:
// add this at THE TOP of the file
session_start();
// check session variable
if(!empty($_SESSION['response']) {
// display the message
echo $_SESSION['response']['message'];
}
Redirect to your login page again. Suppose, LoginForm.php
Updated code:
<?php session_start();
include 'db.php';
if(isset($_POST['submit_login']))
{
if(!empty($_POST['user_name']) && !empty($_POST['password']))
{
$get_user_name = mysqli_real_escape_string($conn,$_POST['user_name']);
$get_password = mysqli_real_escape_string($conn,$_POST['password']);
// Encrypting the password from text//
$get_password=md5($get_password);
$sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password'" ;
if($result = mysqli_query($conn,$sql))
{
while($rows = mysqli_fetch_assoc($result))
{
if(mysqli_num_rows($result) == 1)
{
$_SESSION['user'] = $get_user_name;
$_SESSION['password'] = $get_password;
$_SESSION['user_role'] = $rows['user_role'];
if($_SESSION['user_role'] === 'admin')
{
header('Location:property-list.php');
}
}
else{
$msg = 'User name or Password was Wrong!';
$msgclass='bg-danger';
}
}
}
else {
$msg = 'There is somekind of Database Issue!';
$msgclass='bg-danger';
}
} else {
$msg = 'User name or Password was empty!';
$msgclass='bg-danger';
}
header("Location:Login.php");
}
?>
If the user enters a wrong password or blank one you are not redirecting it to anywhere.
see updated code.
<?php session_start();
include 'db.php';
if(isset($_POST['submit_login'])){
if(!empty($_POST['user_name']) && !empty($_POST['password'])){
$get_user_name = mysqli_real_escape_string($conn,$_POST['user_name']);
$get_password = mysqli_real_escape_string($conn,$_POST['password']);
// Encrypting the password from text//
$get_password=md5($get_password);
$sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password'" ;
if($result = mysqli_query($conn,$sql)){
while($rows = mysqli_fetch_assoc($result)){
if(mysqli_num_rows($result) == 1){
$_SESSION['user'] = $get_user_name;
$_SESSION['password'] = $get_password;
$_SESSION['user_role'] = $rows['user_role'];
if($_SESSION['user_role'] === 'admin'){
// redirect to members area or login area
header('Location:property-list.php');
exit();
}
}
else{
$msg = 'User name or Password was Wrong!';
$msgclass='bg-danger';
}
}
}
else {
$msg = 'There is somekind of Database Issue!';
$msgclass='bg-danger';
}
} else {
$msg = 'User name or Password was empty!';
$msgclass='bg-danger';
}
}else {
}
// redirect to error page or login page..
header("redirect:error.php?msg=$msg&c=$msgClass");
exit();
?>
Some developers pass the variables with get others set a session and read the session. Is your choice I prefer sessions, but if you use GET or POST please always sanitize the user input.
On the query you should update your code to use prepared statements to eliminate possibilities of SQL injection.
On the password you are using MD5 if you are going to use it or either hashing protocol you should salt it so your passwords are stronger in case your sql is expose and the hashes are obtain.
$salt = "s0meRand0mStr1ng..Long..difficult...etc."; // must be longer than 20 chars at least.
$get_password=md5($get_password . $salt);
This worked fine for me
<?php session_start();
include 'db.php';
if(isset($_POST['submit_login'])){
if(!empty($_POST['user_name']) && !empty($_POST['password'])){
$get_user_name = mysqli_real_escape_string($conn,$_POST['user_name']);
$get_password = mysqli_real_escape_string($conn,$_POST['password']);
// Encrypting the password from text//
$get_password=md5($get_password);
$sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password' limit 0,1" ;
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) == 1){
$_SESSION['user'] = $get_user_name;
$_SESSION['password'] = $get_password;
$_SESSION['user_role'] = $row ['role'];
if($_SESSION['user_role'] === 'admin'){
header('Location:property-list.php');
exit;
}
}
else{
header('Location:index.php?msg=1');
exit;
}
} else {
header('Location:index.php?msg=3');
exit;
}
}
if(isset($_GET['msg']) && !empty($_GET['msg'])){
if($_GET['msg']==1){
$msg = 'User name or Password was Wrong!';
$msgclass='bg-danger';
}else if($_GET['msg']==2){
$msg = 'User name or Password was empty!';
$msgclass='bg-danger';
}
}
?>
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'm having trouble redirecting to the same page. I keep getting the message: "The localhost page isn’t working, localhost redirected you too many times, ERR_TOO_MANY_REDIRECTS".
From my navbar there are drop downs for registering and logging in. Registering worked fine and so did the login for a few minutes then suddenly stopped working for some reason. I hadn't touched the code in over an hour.
<?php
session_start();
if(isset($_SESSION['usr_id'])) {
header("Location: index.php");
}
include_once 'dbconnect.php';
//set validation error flag as false
$error = false;
//check if form is submitted
if (isset($_POST['signup'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);
//name can contain only alpha characters and space
if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$name_error = "Name must contain only alphabets and space";
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$error = true;
$email_error = "Please Enter Valid Email ID";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($password != $cpassword) {
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (!$error) {
if(mysqli_query($con, "INSERT INTO users(name,email,password) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
$successmsg = "Successfully Registered! <a href='login.php'>Click here to Login</a>";
} else {
$errormsg = "Error";
}
}
}
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
header("Location: index.php");
die;
} else {
$errormsg = "Incorrect Email or Password!!!";
}
}
?>
<div class="wraplogin">
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="loginform" id="edd_login_form" class="edd_form">
<fieldset>
<legend>Log into Your Account</legend>
<p>
<label>Username</label>
<input type="text" name="email" required class="form-control" id="edd_user_login" class="required edd-input" />
</p>
<p>
<label>Password</label>
<input type="password" name="password" placeholder="Your Password" required class="form-control" id="edd_user_pass" class="password required edd-input" />
</p>
<p>
<input id="edd_login_submit" type="submit" class="edd_submit" name="login" value="Log In" />
</p>
<li class="divider"></li>
<p class="edd-lost-password">
Lost Password?
</p>
</fieldset>
</form>
<span class="text-danger"><?php if (isset($errormsg)) { echo $errormsg; } ?></span>
</div>
Anyone know what the issue is?
Right at the beginning you do a redirect:
<?php
session_start();
if(isset($_SESSION['usr_id'])) {
header("Location: index.php");
}
However after logged in ($_SESSION['usr_id'] is set) if this page is index.php, it will redirect to itself, and check again and redirect to itself, again, entering a loop