Change signup page echo message based on if statement from different page - php

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>

Related

Display data of the user after logging in

This is my form of cus_login.php:
<form method="post" action="cus_login.php">
<h2>LOG-IN</h2> <hr>
<div id="message" > <?php if ($msg != "") echo $msg ?></div>
<div class="form-group">
<input class="form-control" name="email_add" type="email" placeholder="Email...">
</div>
<div class="form-group">
<input class="form-control" name="password" type="password" placeholder="Password...">
</div>
<input class="btn btn-success" type="submit" name="submit" value="LOG IN">
</form>
The action is just above this file, which is the following:
<?php include 'includes/config.php';
session_start();
if (isset($_POST['submit'])) {
$email_add = $con->real_escape_string($_POST['email_add']);
$password = $con->real_escape_string($_POST['password']);
if ($email_add == "" || $password == "")
$msg = "Empty Fields! Type in your Email address and Password";
else {
$sql = $con->query("SELECT * FROM tbl_customers WHERE email_add='$email_add'");
if ($sql->num_rows > 0) {
$data = $sql->fetch_array();
if (password_verify($password, $data['password'])) {
if ($data['confirm'] == 0)
$msg = "Please verify your email! Before logging in";
else {
session_start();
$_SESSION['id'] = $row['id'];
header("location: cus_prof.php");
}
} else
$msg = "Wrong Password! Please enter again.";
} else {
$msg = "Wrong Email Address! Please enter again";
}
} }?>
How do I display the info of the customers based on the email or id to another page or file ... like a profile information page?
<?php
session_start();
include 'includes/config.php';
/*note in your config.php must have the session_start(); function as the first line just after
opening php tag else session will not start and Your session variable will not be available */
$msg="";
if (isset($_POST['submit'])) {
$email_add = $con->real_escape_string($_POST['email_add']);
$password = $con->real_escape_string($_POST['password']);
if ($email_add == "" || $password == "")
$msg = "Empty Fields! Type in your Email address and Password";
else {
$sql = $con->query("SELECT * FROM tbl_customers WHERE email_add='$email_add'");
if ($sql->num_rows > 0) {
$data = $sql->fetch_array();
if (password_verify($password, $data['password'])) {
if ($data['confirm'] == 0)
$msg = "Please verify your email! Before logging in";
else {
// session_start(); this must be call in the first line of code before any other code
$_SESSION['id'] = $row['id'];
//here you can just add the data variable to the session`enter code here`
//$_SESSION['data'] = $data;
header("location: cus_prof.php");
}
} else
$msg = "Wrong Password! Please enter again.";
} else {
$msg = "Wrong Email Address! Please enter again";
}
}
}?>
// then in your cus_prof.php file
<?php
include 'includes/config.php';
$id =$_SESSION['id'];
$sql = $con->query("SELECT * FROM tbl_customers WHERE id='$id'");
if ($sql->num_rows > 0) {
$data = $sql->fetch_array();
//do whatever you want with the data in the $data array
}
?>
I have just added the data variable to session that way you can access whatever is in the data variable through the session variable at any location.

How to display validation errors in my website?

I just want this PHP code to display form validation errors in my website whenever someone uses the form incorrectly. Here is the code and I will also include the HTML of the form.
The code is only for reference, if you have a better way of doing it, then please show me.
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$number = mysqli_real_escape_string($conn, $_POST['number']);
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
// Error handlers
// Check for empty fields
if (empty($first) || empty($last) || empty($email) || empty($number) || empty($uid) || empty($pwd)) {
header("Location: ../signup.php?signup=empty");
exit();
} else {
// Check if input characters are valid
if (!preg_match("/^[a-zA-Z'-]+$/",$first) || !preg_match("/^[a-zA-Z'-]+$/",$last)) {
header("Location: ../signup.php?signup=invalid");
exit();
} else {
// Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=invalidemail");
exit();
} else {
if (preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $number)) {
header("Location: ../signup.php?signup=invalidnumber");
exit();
} else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultcheck = mysqli_num_rows($result);
if ($resultcheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
} else {
// Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
// Insert the user into the database
$sql = "INSERT INTO users (user_first, user_last, user_email, user_number, user_uid, user_pwd) VALUES ('$first', '$last', '$email', '$number', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
header("Location: ../accountcreated.php");
exit();
}
}
}
}
} else {
header("Location: ../signup.php");
exit();
}
Here is the HTML code:
<form class="memberform" action="includes/signup.inc.php" method="POST" novalidate>
<input id="spfirst" class="form_fname" type="text" name="first" placeholder="First Name">
<span class="error_form"></span>
<input id="splast" class="form_lname" type="text" name="last" placeholder="Last Name">
<span class="error_form"></span>
<input class="form_email" type="email" name="email" placeholder="E-mail">
<span class="error_form"></span>
<input id="spnumber" class="form_tel" type="tel" name="number" placeholder="Phone number">
<span class="error_form"></span>
<input id="spuser" class="form_user" type="text" name="uid" placeholder="Username">
<span class="error_form"></span>
<input class="form_password" type="password" name="pwd" placeholder="Password">
<span class="error_form"></span>
<button type="submit" name="submit">Create Account</button>
</form>
Okay there it is. I already tried so many things a nothing seems to work... Maybe it's due to my limited knowledge with PHP.
This is not the best way to do it in my opinion, but following your current code, I suggest you do this.
In your signup.php file, add this where you want the error message to appear (within the HTML if you want):
<?php
if(isset($_GET['signup'])){
switch($_GET['signup']){
case 'empty':
$msg = 'Empty fields';
break;
case 'invalid':
$msg = 'Invalid input';
break;
case 'invalidemail':
$msg = 'Invalid email';
break;
case 'invalidnumber':
$msg = 'Invalid number';
break;
case 'usertaken':
$msg = 'User taken';
break;
default:
$msg = ''; // Default message, if any
break;
}
echo '<div class="error_div">'.$msg.'</div>'; // here's where the message appears
}
?>
That will show your messages. Obviously, feel free to change the class name and style it as you wish.
Or you can simply do something like this (changing the text and stuff depending on the result you're looking for):
<?php
if(isset($_GET['signup'])){
if($_GET['signup'] == 'empty'){
echo '<span class="error_form">Empty values</span>';
}
}
?>
Since you're redirecting users to the signup page with a specific error message (Example: usertaken), you can use $_GET to handle the errors.
So in your signup page, do this
$error should = "" ;
if(isset($_GET['signup'])) {
$error = $_GET['signup'];
if(!empty($error){
//check for specific errors
if($error == "usertaken"){
$errorMsg = "The username has already been taken, try again";
}
}
}
You can use the $errorMsg in your HTML and put it where you want to display the error and design it accordingly.
NOTE: I have not done any sanitization, trying to keep this short.

I got usernames to display on my site, but when I log in the username disappears

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");
}

PHP login form not working with mysql

<?php
if(array_key_exists("logIn",$_POST))
{
$link = mysqli_connect("dbaddress", "dbname", "dbpassword", "dbuser");
if(!$_POST['regno'])
{
$error .= "Please enter your registration number";
}
if(!$_POST['password'])
{
$error .= "Password is required!";
}
if($error!="")
{
echo "<p>There were errors in your forms!</p>".$error;
}
else
{
$query = "SELECT * FROM `users` WHERE RegistrationNo = '".mysqli_real_escape_string($link, $_POST['regno'])."'";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
if (isset($row)) {
$hashedPassword = md5(md5($row['id']).$_POST['password']);
if ($hashedPassword == $row['password']) {
$_SESSION['id'] = $row['id'];
header("Location: after_login.php");
}
else {
$error = "That email/password combination could not be found.";
}
}
else {
$error = "That email/password combination could not be found.";
}
}}
?>
<form method="post">
<center><input type="text" placeholder="Enter Username" name="regno" id="log_username" class="sidelog"/>
<input type="password" placeholder="Enter Password" name="password" id="real_pass" class="sidelog"/>
</br><button id="button_log" type="submit" name="logIn" > GO </button> </center>
</form>
The page reloads whenever I fill the form and submit it. The header isn't working. I can't seem to figure out why.If i leave the form empty, the error string is showing up properly. I used md5 encryption for the password. I concatenated the md5 of id in the database with the password and md5 encrypted the resulting string.
Try this will may help you,
if ($hashedPassword == $row['password']) {
$_SESSION['id'] = $row['id'];
header("Location: after_login.php");
die();
}

Login / Registration PHP form

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

Categories