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
Related
I am practicing PHP and database creation and would like to change my message based on errors from the input. I can't figure out how to pass the changed messaged back and would appreciate any help given.
This is my sign up page
<main>
<h1>Signup<h1>
<h3>
<?php
echo $errorMsg;
?>
<h3>
<form action="includes/signup.inc.php" method="post">
<input type="text" name="uid" placeholder="Username">
<input type="text" name="mail" placeholder="E-mail">
<input type="password" name="pwd" placeholder="Password">
<input type="password" name="pwd_repeat" placeholder="Repeat Password">
<button type="submit" name="signup-submit">Submit</button>
<form>
</main>
This is my processing page
if(isset($_POST['signup-submit'])){
require 'dbh.inc.php';
$Name = $_POST['uid'];
$Email= $_POST['mail'];
$Password = $_POST['pwd'];
$PasswordRepeat = $_POST['pwd_repeat'];
if(empty($Name) || empty($Email) || empty($Password) || empty($PasswordRepeat)){
header("Location: ../signup.php?error=emptyfields=1"); //Check if any field is empty
exit();
}
else if(!filter_var($Email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $Name)){
header("Location: ../signup.php?error=invalidamil&uid"); //Check if username and email is valid input
exit();
}
else if(!filter_var($Email, FILTER_VALIDATE_EMAIL)){
header("Location: ../signup.php?error=invalidamil&uid=".$Name); //Check if email is valid input
exit();
}
else if($Password !== $PasswordRepeat){
header("Location: ../signup.php?error=passwordCheck&uid=".$Name."&mail=".$Email); // Check if passwords don't match
exit();
}
$sql2 = "SELECT UserName FROM dbo.MainTable WHERE UserName = ?";
$params2 = array($Name, SQLSRV_PARAM_IN);
$stmt2 = sqlsrv_query($conn, $sql2, $params2);
if($stmt2 === false)
{
die(print_r(sqlsrv_errors(), true));
exit();
}
$row_count = sqlsrv_num_rows($stmt2);
if($row_count != 0)
{
$_SESSION['errMsg'] = "Error retrieving username";
header("location: ../register.php");
exit();
}
else if($row_count > 0)
{
$_SESSION['errMsg'] = "Username is already used";
header("Location: ../signup.php?error=UserNameTaken&uid");
exit();
}
else{
$sql = "INSERT INTO dbo.MainTable(UserName,Email,UserPassword)
VALUES (?,?,?)";
$Password = PASSWORD_HASH($_POST['pwd'], PASSWORD_DEFAULT); //Password hashing
$stmt = sqlsrv_query($conn, $sql,array(#$Name,#$Email,#$Password));
if($stmt === false){
die( print_r( sqlsrv_errors(), true));
}else{
$_SESSION['errMsg'] = "Registration completed!";
header("Location: ../signup.php?signup=COMPLETE");
exit();
}
}
I am not sure where to put a change message variable here because I couldn't get it work in the if statements.
You are providing the error message as an url paramenter, so you can access it with php $_GET
<h3>
<?php
echo $_GET['error'];
?>
<h3>
I am creating a login form for a website that should redirect the user to the index page after they log in. The problem I'm having is that when I enter the details for logging in, it runs the error part of the code and I can't seem to figure out where I went wrong. I have gone through my code and even physically compared both the passwords and username and they match. Please help me with where I went wrong.
config.php
<?php
session_start();
$host = 'localhost';
$host_user = 'root';
$host_pass = '';
$db_name = 'the_dms_db';
$conn = mysqli_connect($host, $host_user, $host_pass, $db_name);
if (!$conn) {
echo 'Could not connect to the database';
}
$name = '';
$surname = '';
$username = '';
$email = '';
$errors = array();
if (isset($_POST['register_user'])) {
// receive inputs
$name = mysqli_real_escape_string($conn, $_POST['name']);
$surname = mysqli_real_escape_string($conn, $_POST['surname']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$c_password = mysqli_real_escape_string($conn, $_POST['c_password']);
// form validation that it is filled correctly
if (empty($name)) {
array_push($errors, "Name is required");
}
if (empty($surname)) {
array_push($errors, "Surname is required");
}
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if ($password != $c_password) {
array_push($errors, "Passwords to not match");
}
// check database to see if user exists
$user_check_query = "SELECT * FROM users WHERE username='$username' OR email = '$email' LIMIT 1";
$result = mysqli_query($conn, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) {
if ($user['username'] === $username) {
array_push($errors, 'Username already exists');
}
if ($user['email'] === $email) {
array_push($errors, 'Email already exists');
}
}
// register user if no errors
$pass_hash = password_hash($password, PASSWORD_BCRYPT);
if (count($errors) == 0) {
$query = "INSERT INTO users (name, surname, username, email, password) VALUES ('$name', '$surname', '$username', '$email', '$pass_hash')";
mysqli_query($conn, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = 'You are now logged in!';
header('location: ./index.php');
}
}
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_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 = password_hash($password, PASSWORD_BCRYPT);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) == 0) {
$_SESSION['username'] = $username;
$_SESSION['success'] = 'You are now logged in!';
header('location: ./index.php');
} else {
array_push($errors, 'Wrong username/password');
}
}
}
signin.php
<?php
require_once './header.php';
include_once './config.php';
?>
<link rel="stylesheet" href="/assets/css/style.css">
<section class="sign-in-section">
<div class="container">
<div class="form-area ">
<h1>Sign In</h1>
<form action="./signin.php" class="signin-form" method="POST">
<?php include './errors.php'; ?>
<section class="input-sections">
<input type="text" class="inputs form-control" name="username" id="username" placeholder="Username or Email">
<input type="password" class="inputs form-control" name="password" id="password" placeholder="Password">
<button type="submit" class="btn-form btn signin-btn" name="login_user" id="login_user">Sign in</button>
</section>
</form>
Not yet a member? Register here!
</div>
</div>
</section>
signup.php
<?php
include './config.php';
require_once './header.php';
?>
<link rel="stylesheet" href="/assets/css/style.css">
<section class="sign-in-section">
<div class="container">
<div class="form-area ">
<h1>Sign up</h1>
<form action="signup.php" class="signup-form" method="post">
<?php include './errors.php' ?>
<section class="input-sections">
<input type="text" class="inputs form-control" name="name" id="name" placeholder="Name" value="<?php echo $name ?>">
<input type="text" class="inputs form-control" name="surname" id="surname" placeholder="Surname" value="<?php echo $surname ?>">
<input type="text" class="inputs form-control" name="username" id="username" placeholder="Username" value="<?php echo $username ?>">
<input type="text" class="inputs form-control" name="email" id="email" placeholder="Email" value="<?php echo $email ?>">
<input type="password" class="inputs form-control" name="password" id="password" placeholder="Password">
<input type="password" class="inputs form-control" name="c_password" id="c_password" placeholder="Confirm Password">
<button type="submit" class="btn-form btn register-btn" name="register_user" id="register">Register</button>
</section>
</form>
Already have an account? Sing in here!
</div>
</div>
</section>
errors.php
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
Shouldn't the returned result have 1 row rather than 0 rows, if it's a match?
Change this
if (mysqli_num_rows($results) == 0)
To this
if (mysqli_num_rows($results) >= 1)
If you ignore the vulnerabilities within the sql statements you should analyse the following to see where you were going astray with the approach above. Using password_hash will generate a new hash on each invocation - so the hashed password will never ( hopefully ) match a newly generated hash. You need to use password_verify instead.
define('BR','<br />');
$password=$_POST['password'];
$query = "SELECT `password` FROM `users` WHERE `username`='$username' LIMIT 1";
$results = mysqli_query( $conn, $query );
$rs=mysqli_fetch_assoc( $results );
if( password_verify( $password, $rs['password'] ) ){
/* OK - The user supplied a good username/password combo */
}else{
/* Bad Foo!!! The supplied password did not verify against the stored hash */
}
If you consider
$pwd='banana';
echo password_hash($pwd,PASSWORD_DEFAULT) . BR;
echo password_hash($pwd,PASSWORD_DEFAULT) . BR;
echo password_hash($pwd,PASSWORD_DEFAULT) . BR;
you will likely see results similar to:
$2y$10$7a4Cvzn51eYa3EJKary8zemJn4/GiFA.2fqYQrwd6QrRORIk552Wm
$2y$10$E5.28SSkQo2lZv11zilkBO1L35umAFzr5Zr2yKScX4nDgFkN.kTbK
$2y$10$HEzHOFT/7V972XDEB9uzRuU/dxHxRnSXs64wu1qdahJs2CSp3wwD6
As you can see they are all different...
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.
having a bit of trouble with my login / reg forms
Basically when i register (create new user) it takes me to the login.php script and not the register script.
The login form is in the "header.php" page so its at the top of every page including the register form. But dont think that would be an issue?
Register form
<?php
include("config.php");
include("header.php");
?>
<div id="contentwrap">
<form name="myuserform" method="POST" action="register.php" onsubmit="return validateForm();">
<tr class='alt'>
<td>email address: <td><input type="text" name="email">
<tr class='alt'>
<td>Password: <td><input type="password" name="password">
<tr class='alt'>
<td>Your name: <td><input type="text" name="username">
<tr class='alt'>
<td><input type="submit" name="adduser" value="Sign me up!">
</form>
</div>
Register.php
<?php
if (isset($_POST['adduser']))
{
$error = "";
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$md5_pass = md5($password);
$email = mysqli_real_escape_string($connection, $_POST['email']);
if (!isset($username) || empty($username) ||
!isset($password) || empty($password) ||
!isset($email) || empty($email))
{
$error = "All fields must be filled out";
}
else if (user_exists($connection, $username))
{
$error = "Username already registered";
}
else if (strlen($password) < 6)
{
$error = "Password must be at least 6 characters";
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // check if email looks valid
{
$error = "Please enter a valid email";
}
if ($error == "")
{
//$query = "INSERT INTO users (email, password, username) VALUES ('{$email}','{$md5_pass}','{$username}')";
$query = "INSERT INTO users (username, password, email) VALUES ('{$username}','{$md5_pass}','{$email}')";
$result = mysqli_query($connection, $query);
if ($result)
echo " <b>Registered successfully!</b><br/>Please return to the <a href='index.php'>index</a> to login.";
else
$error = "Unable to create new user";
}
if ($error != "") // redo error string check since the last block may have set it
{
echo "Error: {$error}. Please return to the previous page.";
}
exit();
}
?>
Login.php
<?php
include("config.php");
if (isset($_POST['username']) && !empty($_POST['username']) &&
isset($_POST['password']) && !empty($_POST['password']))
{
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = md5($_POST['password']);
$query = "SELECT * FROM users WHERE username='{$username}' AND password='{$password}'";
$res = mysqli_query($connection, $query);
if (mysqli_num_rows($res) >= 1)
{
$row = mysqli_fetch_array($res);
if($row['rank'] == "banned")
{
echo "You have been banned from the site.";
exit();
}
$_SESSION['uid'] = $row['userid'];
$_SESSION['username'] = $row['username'];
if($row['rank'] == "admin")
$_SESSION['is_admin'] = true;
header("Location: index.php");
exit();
}
else
{
echo "Username/password invalid. Return to the <a href='index.php'> home </a>page";
exit();
}
}
echo "Something went wrong, try again"; <--- this is the result im getting
?>
here is the login form (apart of header.php)
<?php
if (!isset($_SESSION['uid']) || empty($_SESSION['uid']))
{
echo "<form action='login.php' method='post'>
Username: <input type='text' name='username' Placeholder='Username' style='width:100px;'/>
Password: <input type='password' name='password' Placeholder='Password' style='width:100px;' />
<input type='submit' name='submit' value='Log In' />";
echo "<div id='freeman'>
<a href='signup.php'> <img src='images/register.jpg' width='60px' height='60px' /> </a>
</div>";
} else {
echo "You are logged is as {$_SESSION['username']} • <a href='logout.php'>Logout</a>";
}
?>
The problem that when you register your not opening a session to consider the user as logged and acquire a session for him.
The other issue your not checking in your login script if the user already have a session which implies that he is already logged in