Echo success or failure on the same page - php

This is my sign-up form.
<div class="tab-content">
<div id="signup">
<h1>Sign Up for Free</h1>
<form action="register.php" method="POST">
<div class="top-row">
<div class="field-wrap">
<label>
Username<span class="req">*</span>
</label>
<input name="username" type="text" required autocomplete="off" />
</div>
<div class="field-wrap">
<label>
E-mail<span class="req">*</span>
</label>
<input name="email" type="text"required autocomplete="off"/>
</div>
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input name="password" type="password"required autocomplete="off"/>
</div>
<div class="field-wrap">
<label>
Repeat password<span class="req">*</span>
</label>
<input name="rpassword" type="password"required autocomplete="off"/>
</div>
<button type="submit" class="button button-block"/>Get Started</button>
</form>
</div>
<div id="login">
<h1>Welcome Back!</h1>
<form action="login.php" method="post">
<div class="field-wrap">
<label>
Username<span class="req">*</span>
</label>
<input name="username" type="text"required autocomplete="off"/>
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input name="password" type="password"required autocomplete="off"/>
</div>
<p class="forgot">Forgot Password?</p>
<button class="button button-block"/>Log In</button>
</form>
</div>
Then the register.php
<?php
session_start();
$host= 'localhost';
$user='root';
$pass='';
$db='gameforum';
$conn=mysqli_connect($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username = $_POST['username'];
$password = $_POST['password'];
$rpassword = $_POST['rpassword'];
$email = $_POST['email'];
if ($password!==$rpassword) {
echo "Passwords did not match, please try again!"
$conn->close();
}
else {
$sql = "INSERT INTO users (username, password, Repeat_Password, email)
VALUES ('$username', '$password', '$rpassword', '$email')";
if ($conn->query($sql) === TRUE) {
$redirectUrl = 'index.php';
echo '<script type="application/javascript">alert("Thank you for your registration! You may now log in with your account!"); window.location.href = "'.$redirectUrl.'";</script>';
}else{
echo "Username or Email already exists!". mysql_error();
}
$conn->close();
}
?>
The problem is that if the passwords do not match then the user comes to a blank page where it says that. I want the errormessage to pop up on the same page the user i signing up on. I do not know how to do that, any ideas?

There are two ways to do this. One is to use sessions, the other one is to redirect user back to login page with something like signin.php?err=invalid_pass
of you do it with a session, you will need this code on top of your sign in page. It will print out error message if you set any in your signin page.
<?php
session_start();
if(isset($_SESSION['err']))
{
echo $_SESSION['err'];
unset($_SESSION['err'];
}
alternatively, you can add this code on top of your sign-in page:
<?php
if(isset($_REQUEST['err']))
echo $_REQUEST['err'];
You will also need to replace your echo "Passwords did not match, please try again!"
with this if you do sessions:
$_SESSION['err']="Passwords did not match, please try again!";
header("Location: signin.php");
and this if you do using the other method.
header("Location: signin.php?err=You_Goofed");

You will need to use ajax on your HTML page. When the user clicks on the form button, instead of submitting the form to the server, use ajax to send the data to the server. Then return the data from the server to the client.
Example:
$('#submit-btn').click(function(e){
$.ajax({
type:'POST',
url:'register.php',
data:{
user:username,
pw:password
}
}.done(function(data){
if(data === false){
alert("passwords don't match!");
}
});
});
In your PHP page, you will validate the passwords. If they don't match, echo false.

Related

how to redirect through user-home page

I am trying to redirect the index page to user-home.php page. but when I am trying to login its showing wrong user. How to redirect to the user-home page by this condition. expecting help. Thanks in advance. The following image is the database property of the signup page.
database of signup
HERE IS MY CODE FOR INDEX PAGE
<form method="post" action="" autocomplete="on">
<h3>Log in</h3>
<hr>
<p>
<label for="username" class="uname" data-icon="u" > Your username </label>
<input id="username" name="username" required="required" type="text"/>
</p>
<p>
<label for="password" class="youpasswd" data-icon="p"> Your password </label>
<input id="password" name="password" required="required" type="password"/>
</p>
<p class="login button">
<input type="submit" name="login" value="Login" />
</p>
</form>
<h2>dont have an account signup here</h2>
<li>signup</li>
</table>
<?php
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$q=$db->prepare("SELECT* FROM signup WHERE username='$username' && password='$password'" );
$q->execute();
$row=$q->fetch(PDO::FETCH_OBJ);
$count = $q->rowcount();
if ($count >= 1){
session_start();
$_SESSION['id'] = $row['user_id'];
header('location:user-home.php');
}else{
echo "<script>alert ('Wrong User')</script>";
}
}
?>

Allow user to login with a username & password & 4-digit pin code

I want user login with username password and 4 digit pin code and code is in my db. Here is my code sample. If any one here can help me I would very much appreciate it:
<?php
if (isset($_POST['login'])) {
$user = $_POST['user'];
$pass = $_POST['pass'];
$pincode = $_POST['pincode'];
if (empty($user) OR empty($pincode)) {
echo "<script>alert('Please Fill All Required Field')</script>";
} else {
$select_user = "select * from users WHERE Username = '$user' AND Password ='$pass' pin-code ='?' ";
$run_user_sql = mysqli_query($conn, $select_user);
$check_customer = mysqli_num_rows($run_user_sql);
if ($check_customer ==false) {
echo "<script>alert('Username/Password Wrong')</script>";
exit();
}
if ($check_customer == true) {
$_SESSION['user'] = $user;
echo "<script>alert('You Are Logged In')</script>";
echo "<script>window.open('index.php?dashboard','_self')</script>";
}
}
}
?>
<form action="" method="post">
<div class="form-group">
<div class="form-label-group">
<input type="text" class="form-control" name="user" placeholder="Username" >
<label">Username</label>
</div>
</div>
<div class="form-group">
<div class="form-label-group">
<input type="password" class="form-control" name="pass" placeholder="Password" >
<label >Password</label>
</div>
</div>
<div class="form-group">
<div class="form-label-group">
<input type="text" class="form-control" name="pincode" placeholder="4-Digit Pin Code" >
<label >4-Digit Pin Code</label>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me">
Remember Password
</label>
</div>
</div>
<input type="submit" class="btn btn-primary btn-block" name="login" value="Login">
</form>
Your code seems to be okay, but with a lot of security risks. However, your SQL command is wrong. Change it to the following:
$select_user = "select * from users WHERE Username = '$user' AND Password ='$pass' AND `pin-code` ='{$pincode}'";

php login script not redirecting to next page

My login.php is as given below, It is not able to take me to welcome.php. Neither it is giving login error. It simply give 500 error page.
<?php
include("db.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$username=mysqli_real_escape_string($db,$_POST['username']);
$password=mysqli_real_escape_string($db,$_POST['password']);
$password=md5($password); // Encrypted Password
$sql="SELECT id FROM admin WHERE username='$username' and passcode='$password'";
$result=mysqli_query($db,$sql);
$count=mysqli_num_rows($db,$result);
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
header("location: welcome.php");
}
else
{
$error="Your Login Name or Password is invalid";
}
}
?>
<div class="wrapper">
<form class="form-signin" action="login.php" method="post">
<h2 class="form-signin-heading">Please login</h2>
<input type="text" class="form-control" name="username" placeholder="User Name" required="" autofocus="" />
</br>
<input type="password" class="form-control" name="password" placeholder="Password" required=""/>
<label class="checkbox">
<input type="checkbox" value="remember-me" id="rememberMe" name="rememberMe"> Remember me
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
</div>
It gives 500 error after I submit usename and password and not able to take me to welcome.php.
If you are using header(Location: something.php), you should load it as first output in php. Or else it will not work.
session_start() will change the HTTP Header.
Instead try below one,
echo "<script>window.location.href='welcome.php';</script>";

PHP multi-step registration process

I am working on a registration system which comprises of 3 total steps.
Step 1 - user enters a username, system searches the database for the
username. IF the username is found, it checks the account status (ie:
no password created, complete but not verified, registered and
verified).
If user is not found, user is directed to Step 2.
If status = no password created, the user is directed to Step 3.
If status = complete but not verified / registered and verified, Display error message.
Step 2 - user enters personal details.
The page stores user inputs
Step 3 - user creates a password, the system connects to the database and INSERTs user info to the user table. A success message is
displayed.
I have managed to figure out and complete the coding for the first 2 steps, by displaying a new form when the previous form has been submitted.
Problem: However, I have just realised that I am unable to retrieve data from the previous form (ie: at step 3 I am unable to retrieve the Username from Step 1). I have tried using the 'header('location: ?user=$uname');' approach however this doest work because the URL gets reset when I submit the new form and I lose the username again. How do I create a proper multi-step form using ONLY PHP and how do I store the input values so I could use them at the last step. Below is my code:
<?php
include 'includes/session_info.php';
if(isset($_SESSION['user_id'])){
header('Location: index.php');
}
$errors = array();
if(empty($_POST['user_info']) === false){
require ('core/dbcon.php');
$usr_email = mysqli_real_escape_string($con, $_POST['email']);
$usr_joined = mysqli_real_escape_string($con, $_POST['joined']);
$usr_recruited = mysqli_real_escape_string($con, $_POST['recruited']);
if($usr_email){
//direct user to password form
}else{
$errors[] = 'Please complete all fields marked with a Red Asterisk.';
}
$form2 = $usr_email.'<br>'.$usr_joined.'<br>'.$usr_recruited;
}
if(empty($_POST['username_chck']) === false){
require ('core/dbcon.php');
$username = mysqli_real_escape_string($con, $_POST['uname']);
$rpt_uname = mysqli_real_escape_string($con, $_POST['r_uname']);
if($username && $rpt_uname){
if($username == $rpt_uname){
$query = mysqli_query($con, "SELECT status FROM users WHERE username = '$username'") or die(mysqli_error($con));
// Display registration form if Username is not found.
if(mysqli_num_rows($query) == 0){
$form1;
}
// Actions performed If username entered already exists in the database.
elseif(mysqli_num_rows($query) == 1){
$status = mysqli_fetch_assoc($query);
if($status['status'] == 0){
$errors[] = '<b>'.$username.'</b> is already registered and awaiting to be verified by our admins. Feel free to contact an Admin via the website or in-game to get verified.';
}elseif($status['status'] == 1){
//header("Location:?create_pwd&user=$username");
}elseif($status['status'] > 1){
$errors[] = '<b>'.$username.'</b> is already registered and verified by our Admins. Please log in to access you account.
If you have forgotten your password you can rest your password <a class="navbar-link error_link" id="intext-link" href="login.php?fp"><b>here</b></a>.';
}
}elseif(mysqli_num_rows($query) > 1){
$errors[] = 'An error has occurred. Looks like a there is more than one member with that username. Please contact the Administrator for assistance.';
}
}else{
$errors[] = 'Please ensure that the username entered in both fields match.';
}
}else{
$errors[] = 'Please complete all required fields.';
}
}
?>
<html>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<?php
if(empty($_POST['username_chck']) === false){
if(empty ($errors) === false){
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Username: </label><br>
<input type="text" name="uname" class="form-control" placeholder="Please enter your Runescape username." id="Uname" required>
</div>
<div class="form-group">
<label for="repeat_Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Repeat Username: </label><br>
<input type="text" name="r_uname" class="form-control" id="repeat_Uname" placeholder="Please re-enter your Runescape username." required>
</div>
<input type="submit" name="username_chck" class="btn btn-default" value ="Next">
</form>
<?php
}else{ echo $reg_uname;
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Email"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Email: </label>
<input type="email" name="email" class="form-control" id="Email" <?php if (isset($_POST['email'])=== true){echo 'value="', strip_tags($_POST['email']),'"';}?>>
</div>
<div class="form-group">
<label for="Joined">Date Joined: </label><br>
<small class="notice">If you do not remember the exact date please select the first day of the month and year you joined (eg: 01/02/2001).</small><br>
<input type="date" name="joined" class="form-control" id="Joined" <?php if (isset($_POST['joined'])=== true){echo 'value="', strip_tags($_POST['joined']),'"';}?>>
</div>
<div class="form-group">
<label for="recruited">Recruited by: </label>
<select name="recruited" class="form-control" id="recruited">
<option value="" selected disabled>Select a Member</option>
<?php
require ('core/dbcon.php');
$usr_qry = mysqli_query($con, "SELECT user_id, username FROM users")or die(mysqli_error($con));
while($usr = mysqli_fetch_array($usr_qry)){
echo '<option value="'.$usr['user_id'].'">'.$usr['username'].'</option>';
}
?>
</select>
</div>
<input type="submit" name="user_info" class="btn btn-default" value ="Next">
</form>
<?php
}
}elseif(empty($_POST['user_info']) === false){
if(empty ($errors) === false){
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Email"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Email: </label>
<input type="email" name="email" class="form-control" id="Email" <?php if (isset($_POST['email'])=== true){echo 'value="', strip_tags($_POST['email']),'"';}?>>
</div>
<div class="form-group">
<label for="Joined">Date Joined: </label><br>
<small class="notice">If you do not remember the exact date please select the first day of the month and year you joined (eg: 01/02/2001).</small><br>
<input type="date" name="joined" class="form-control" id="Joined" <?php if (isset($_POST['joined'])=== true){echo 'value="', strip_tags($_POST['joined']),'"';}?>>
</div>
<div class="form-group">
<label for="recruited">Recruited by: </label>
<select name="recruited" class="form-control" id="recruited">
<option value="" selected disabled>Select a Member</option>
<?php
require ('core/dbcon.php');
$usr_qry = mysqli_query($con, "SELECT user_id, username FROM users")or die(mysqli_error($con));
while($usr = mysqli_fetch_array($usr_qry)){
echo '<option value="'.$usr['user_id'].'">'.$usr['username'].'</option>';
}
?>
</select>
</div>
<input type="submit" name="user_info" class="btn btn-default" value ="Next">
</form>
<?php
}else
echo $reg_uname.'<br>'. $reg_email.'<br>'.$reg_joined.'<br>'.$reg_recruited.'<br>';
}else{
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Username: </label><br>
<input type="text" name="uname" class="form-control" placeholder="Please enter your Runescape username." id="Uname" required>
</div>
<div class="form-group">
<label for="repeat_Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Repeat Username: </label><br>
<input type="text" name="r_uname" class="form-control" id="repeat_Uname" placeholder="Please re-enter your Runescape username." required>
</div>
<input type="submit" name="username_chck" class="btn btn-default" value ="Next">
</form>
<?php
}
?>
</div>
</div>
</html>
Ps. I have looked into creating a session which gets destroyed when the user navigates away from the page Destroy PHP session on page leaving. However I find that it's not very user friendly as it doesn't work properly if the user has multiple tabs open. I understand that I need to implement a javascript function to make it work properly. I do not know how to code in javascript and would really appreciate your assistance on making a better multi-step registration process.
As mentioned above, store the POST data from each step in the session variable.
// Step 1 submit
$_SESSION['steps'][1] = $_POST;
// Step 2 submit
$_SESSION['steps'][2] = $_POST;
// Step 3 submit
$_SESSION['steps'][3] = $_POST;
You can then use something like currentStep in the session to determine where they last were.
$currentStep = $_POST['step'];
And compare to what data you need available, or just use it directly from the array.
I opted to follow the 'hidden variable' method where I store the values form the previous form in hidden inputs of the current form. Thus enabling me to pass the values on to the next form. A sort of snowball effect, if you will. Below is an example:
Form 1
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Uname">Username: </label><br>
<input type="text" name="uname" class="form-control" id="Uname" required>
</div>
<div class="form-group">
<label for="repeat_Uname">Repeat Username: </label><br>
<input type="text" name="r_uname" class="form-control" id="repeat_Uname" required>
</div>
<input type="submit" name="username_chck" class="btn btn-default" value ="Next">
</form>
Form 2
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Email">Email: </label>
<input type="email" name="email" class="form-control" id="Email" required <?php if (isset($_POST['email'])=== true){echo 'value="', strip_tags($_POST['email']),'"';}?>>
</div>
<input type="hidden" name="username" <?php if (isset($_POST['username'])=== true){echo 'value="', strip_tags($_POST['username']),'"';}else{echo "value=\"$username\"";}?>>
<input type="submit" name="user_info" class="btn btn-default" value ="Next">
Explanation
Below is a skeleton of my code which should help you understand how I have displayed the forms
if(empty($_POST['form1'])=== false){
$username = mysqli_real_escape_string($con, $_POST['username']);
// display form 2
}elseif(empty($_POST['form2'])=== false){
//display form 3
}
Note the hidden input type before the submit button in the second form.
While I have opted to include the if statements within the tags for the sake of this example, you could alternatively choose to process the forms at the top of your page (before the tag).

PHP Session - Form Submit Logs Out User

I have a member form that requires a password to gain access to it.
Once the user has entered the password they may then enter in their details in the form.
However the problem is that when the user submits the form they are getting logged out of the session.
I would like the user to remain logged in when they hit submit and then be directed to a second member form further down the same page.
Here is the code I am using for the password login:
`
<?php
//encrypted password here - example is 'hello'
$password = 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d';
session_start();
session_unset();
session_destroy();
if (!isset($_SESSION['loggedIn'])) {
$_SESSION['loggedIn'] = false;
}
if (isset($_POST['password'])) {
if (sha1($_POST['password']) == $password) {
$_SESSION['loggedIn'] = true;
} else {
header ("Location: error.php");
exit();
}
}
if (!$_SESSION['loggedIn']): ?>
<html>
<head><title>Login Page</title></head>
<body>
<form method="post" action="registration/signup.php">
Password: <input type="password" name="password"> <br />
<input type="submit" name="submit" value="Login">
</form>
</body>
</html>
`
Here is the code I am using at the top of the password protected page (Member Form Page):
<?php
require('../access.php');
?>
And this is the form on the password protected page (Member Form Page):
<form action="#sky-form2" method="post" enctype="multipart/form-data" id="sky-form" class="sky-form">
<fieldset>
<div class="row">
<div class="col-md-4" align="left">
<label class="input">
<input type="text" name="name" placeholder="Name">
<b class="tooltip tooltip-bottom-left">Enter you full name</b>
</label>
</div>
<div class="col-md-4" align="left">
<label class="input">
<input type="email" name="email" placeholder="E-mail">
<b class="tooltip tooltip-bottom-left">Enter a valid email address</b>
</label>
</div>
</div>
</fieldset>
<div class="row">
<div class="col-md-4" align="left">
<button type="submit" button class="border-button">NEXT</button>
</div>
</div>
</form>
I know that the password method above is not the most secure, however I really dont require it to be. I just want the member form to be available to everyone who has been given a password for it.
Huge thank you to anyone who can help me out with this.

Categories