i have a registration form where it has a password field and a confirm password field. I would like the password and confirm password fields to be the same so it can register the new users information.
form:
<form class="form-signin" name="Register_Form" method="post" action="regcheck.php">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" name="inputPassword" class="form-control" placeholder="Password" required>
<label for="CPassword" class="sr-only">Confirm Password</label>
<input type="password" id="CPassword" name="CPassword" class="form-control" placeholder="Confirm Password" required>
<button class="btn btn-lg btn-primary btn-block" type="reg" name="reg" value="Register">Register</button>
</form>
require_once 'connect.php';
if (isset($_POST['reg'])){
//$dob = $_POST['date'];
$dob = date('Y-m-d', strtotime($_POST['date']));
$Student_ID = $_POST['Student_ID'];
$gender = $_POST['gender'];
$course = $_POST['Course'];
$email = $_POST['inputEmail'];
$password = $_POST['inputPassword'];
$cpassword = $_POST['CPassword'];
$FN = $_POST['FirstName'];
$SN = $_POST['SecondName'];
if ($password === $cpassword) {
// success!
$sql = "INSERT INTO tblaccounts (Email, Password, Student_ID, FirstName, SecondName, Course, Gender, DoB) VALUES ('".$email."','".$password."','".$Student_ID."','".$FN."','".$SN."','".$course."','".$gender."','".$dob."')";
$result = mysqli_query($connection, $sql) or die("Database Connection Failed" . mysqli_error($connection));
//$count = mysqli_num_rows($result);
echo "Registeration Successful!:";
header('Location: login.php');
}
else {
// failed :(
}
} else {
echo "Registeration Failed!:";#
?><br/>Go back to the login screen.<?php
}
I'm not sure to understand your question, in fact your code seems (in a crude way) to achieve your goal. However your script will fail at the time to redirect to login.php using header(), due you already have sent information to the client. That happens when you process your data in the same script you have used to display the form fields. I recommend you to send the form's data to another script.
Related
I created a registration form using HTML, created a database called “web_app_dev" and linked the form to the database using PHP, however, when I test the form and click the Submit button nothing happens. It doesn't show me any errors and the information does not get posted into the database.
The table in the database is called "registration"
Below is the code for the "registerform.php"
<?php
session_start();
$FirstName = "";
$LastName = "";
$gender = "";
$email = "";
$password = "";
$errors = array();
// connect to database
$conn = mysqli_connect('localhost', 'root', '', 'web_app_dev');
// check if the registration button is clicked
if (isset($_POST['reg_btn'])) {
// Receive information from the form
$FirstName = mysqli_real_escape_string($conn, $_POST['FirstName']);
$LastName = mysqli_real_escape_string($conn, $_POST['LastName']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// make sure that the form is correctly filled
if (empty($FirstName)) {
array_push($errors, "First Name is required");
}
if (empty($LastName)) {
array_push($errors, "Last Name is required");
}
if (empty($gender)) {
array_push($errors, "Gender is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
//check if user already exists in the database
$user_check = "SELECT * FROM registration WHERE email='$email' LIMIT 1";
$result = mysqli_query($conn, $user_check);
$user = mysqli_fetch_assoc($result);
if ($user) {
if ($email['email'] == $email) {
array_push($errors, "A user with this email already exists");
}
}
//register the user if there are no errors
if (count($errors) == 0) {
$password = md5($password); //encrypt the password before saving it into the database
$query = "INSERT INTO registration (FirstName, LastName, gender, email, password)
VALUES('$FirstName', '$LastName', '$gender', '$email', '$password')";
mysqli_query($conn, $query);
$_SESSION['success'] = "Registration successful!";
}
}
?>
Below is the code from the html file that contains the html code for the form, the file's name is "regform.php"
<?php include('registerform.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" href="edits.css">
</head>
<body>
<style>
body {
background-image: url("img/bg2.jpg");
}
</style>
<div class="header">
<h2 style="margin-right: 60px;">Register</h2>
</div>
<form method="post" action="registerform.php">
<div class="input-group">
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName"
placeholder="Enter First Name..."/>
</div>
<div class="input-group">
<label for="LastName">Last Name</label>
<input type="text" name="LastName" id="LastName"
placeholder="Enter Last Name..."/>
</div>
<div class="radio-group">
<label for="m"><input type="radio" name="gender"
value="m">Male</label>
<label for="f"><input type="radio" name="gender"
value="f">Female</label>
</div>
<div class="input-group">
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder="Enter
Email...">
</div>
<div class="input-group">
<label for="password">Password</label>
<input type="text" name="password" id="password"
placeholder="Enter password...">
</div>
<div class="input-group">
<button type="submit" class="btn" id= "reg_btn"
name="reg_btn" value="reg_btn">Submit</button>
</div>
</form>
</body>
</html>
[Edit] Bellow is a screenshot of the error message that shows, after adding the error reporting code before the mysqli_connect() code.
Error message after filling in the form and clicking the register button
"Line 59" from the error message, is referring to the second last line from the registerform.php code. the code on that line is;
mysqli_query($conn, $query);
The data I put in the form is also shown bellow
Data inserted in the form
It's because you're inserting a hash of the password into the database, not the original password the user entered. md5 hashes usually come out at 32 characters (regardless of the length of the hashed data).
Note that - as you were warned above - md5 is obsolete now and insecure, it can be cracked easily. So should switch to using php's secure password_hash function. As per its documentation you need to allow at least 60 characters for storing a hash created by that function (but it advises 255 is better)
my code generating fetal error in the code it check all fields except cnic filed, a cnic already exist in table in multiple rows.When we try to create login for new member with same cnic it create duplicate entry rather to checking and generate error for the already exiting cnic. i mean to say it check both email and cnic if both exit it deny for new registration but in my case some time it check and some time it not check the email and cnic. Please correct my code i try a lot but i am unable to filed where i'm doing wrong.Your help in this regard will highly helpful for me and i will be highly thankful to you.
<?php
//Start the Session
require_once("config.php");
//error_reporting(0);
$headers ='';
$res = '';
$Message = '';
$Message1 = '';
$Message2 = '';
$recaptcha = '';
$query ="SELECT * FROM tbl_signup;";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
$user_cnic = $row['apli_cnic'];
$User_Email = $row['apli_email'];
if(isset($_POST['ButtonSignUp']))
{
$Cnic=mysqli_real_escape_string($conn, $_POST['cnic']);
$Name= mysqli_real_escape_string($conn,$_POST['namesurname']);
$Email = mysqli_real_escape_string($conn, $_POST['email']);
$Password = mysqli_real_escape_string($conn, $_POST ['password']);
$CnfrmPassword = mysqli_real_escape_string($conn, $_POST['confirmPassword']);
$ActivationCode = md5( rand(0,1000) );
$Status = 0;
if ($Cnic == $user_cnic)
{
$Message = "Sign Up Failed. Account With CNIC: $user_cnic Already Exist";
}
elseif($Email == $User_Email)
{
$Message1 = "$Email Already Exist. Please Enter Another Email Address.";
}
elseif($Password != $CnfrmPassword)
{
$Message2 = "Your Password does not match the Confirm Password";
}
elseif ($Password == $CnfrmPassword)
{
$sql= "INSERT INTO table(fname, email, cnic, pwd, cnfrm_pwd, activation_code, status)
VALUES ('$Name','$Email','$Cnic','$Password','$CnfrmPassword', '$ActivationCode', '$Status');";
mkdir("DocumentUpload/$Cnic");
$to_email = $Email;
$subject = 'Verify Your Email';
$message = "Your account information is successfully updated. Please click the following link For verifying and activate your account.
$headers = 'From: abc.com
$res = mysqli_query($conn, $sql);
if(mail($to_email, $subject, $message, $headers))
{
}
}
if($res == 1)
{
header("location:VerifyEmailWait.php");
}
else
{
}
}
mysqli_close($conn);
?>
<form id="sign_up" method="POST">
<input type="number" class="form-control" name="cnic" placeholder="CNIC e.g. 3520212345678" maxlength="13" required autofocus autocomplete="off">
<input type="text" class="form-control" name="namesurname" placeholder="Full Name (As Per CNIC)" required autofocus autocomplete="off">
<input type="email" class="form-control" name="email" placeholder="Email Address" required autocomplete="off">
<input type="password" class="form-control" name="password" id="password" minlength="8" placeholder="Password" required autocomplete="off">
<input type="password" class="form-control" name="confirmPassword" id="confirmPassword" minlength="8" placeholder="Confirm Password" required autocomplete="off">
<button class="btn btn-block btn-lg bg-pink waves-effect" type="submit" name="ButtonSignUp">SIGN UP</button>
Already a Member? Please Sign In
</form>
Your insert statement
INSERT INTO table(fname, email, cnic, pwd, cnfrm_pwd, activation_code, status)
VALUES ('$Name','$Email','$Cnic','$Password','$CnfrmPassword', '$ActivationCode', '$Status');
is wrong it must be
INSERT INTO tbl_signup(fname, email, cnic, pwd, cnfrm_pwd, activation_code, status)
VALUES ('$Name','$Email','$Cnic','$Password','$CnfrmPassword', '$ActivationCode', '$Status');
Where you use the proper tabke name a generic table like you did is not allowed.
But please read this about passwords
And of course that about preventing sql injection
Before you proceed in your development.
I am learning MySQL and PHP and I trying to build a simple login webpage and connect with MySQL.
I have built the page with HTML and CSS, also I downloaded PHP and installed MySQL, I am getting confused about how to combine those things and when I input my password and username it will go to successful page.
I am not seeking an answer but need some suggestions for the next step.
PLEASE NOTE - the way my SQL queries are written here are open to SQL injection (see here to get the changes you would need to make)
So to start. You want to create a database table to store your users, a form to create users, and some code to query the data into the database.
i would start with a form like this:
<form method="post" class="mt-3">
<input type="hidden" name="do" value="create" />
<div class="form-group">
<label for="itemName">First Name</label>
<input type="text" class="form-control" name="firstName">
</div>
<div class="form-group">
<label for="serialNumber">Last Name</label>
<input type="text" class="form-control" name="lastName">
</div>
<div class="form-group">
<label for="serialNumber">Username</label>
<input type="text" class="form-control" name="userName">
</div>
<div class="form-group">
<label for="serialNumber">Password</label>
<input type="password" class="form-control" name="passWord">
</div>
<a id="create-member" class="btn btn-success text-white">Submit</a>
</form>
then you want some code that will take the values you have in that form and turn them into a query to add that info into your table.
if(isset($_POST['do'])) && $_POST['do'] == 'create'
{
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$username = $_POST['userName'];
$password = password_hash($_POST['passWord'], PASSWORD_BCRYPT);
$sql = "INSERT INTO members (first_name, last_name, username, password) VALUES ('".$firstName."', '".$lastName."', '".$username."', '".$password."')";
mysqli_query($conn, $sql); //$conn is set in my header file and included into every page.
}
That is pretty much the process for creating a user and adding it to your table, obviously you'll have to break it down and change values to what you have in your table etc.
Next it's the case of verifying a login.
first, a login form:
<form method="post">
<input type="hidden" name="do" value="login" />
<div class="form-group">
<label for="usename">Username</label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
and then an authentication query to follow, this will take the info in the login page, hash the password you entered and then compare it with the one in your database.
if (isset($_POST['do']) && $_POST['do'] == 'login')
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT id, first_name, last_name, password FROM members WHERE username= '$username'";
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if($query->num_rows == 0)
{
echo "Username or password incorrect";
}else{
$data = mysqli_fetch_array($query);
if(!password_verify($password, $data['password']))
{
echo "Username or password incorrect";
}else{
session_regenerate_id();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['member_id'] = $data['id'];
$_SESSION['first_name'] = $data['first_name'];
$_SESSION['last_name'] = $data['last_name'];
}
}
}
}
?>
don't be scared about the $_SESSION variables at the bottom, i just set all user data as that so it's easier to access it on other pages, then i just follow with a header to my index.php page. In my header i also check to see that $_SESSION['loggedin'] is set to true and if not it redirects them to the login page (also be care to take into account the user might be on the login page, you dont want a redirect error)
This is my first detailed answer on this site so i hope it helps you :)
I have 2 problems.
Basic story: I have created a SIMPLE registration and login system.
Problem1: If I try to register a new account then it says "user registration failed". At the moment it should say that because mysql can't get right information from forms. But problem is that I don't know why. Everything seems correct...
Problem2: If I try to login with existent account then it seems that browser is only refreshing the page and nothing else...
Registration with php code:
<?php
require ('insert.php');
// If values posted, insert into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$name = $_POST['name'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
// nimi refers to name, it's correct
$query = "INSERT INTO `user` (nimi, email, username, password)
VALUES('$name', '$email', '$username', '$password')";
//POST retrieves the data.
$result = mysqli_query($connection, $query);
if($result){
$smsg = "User Created Successfully.";
} else {
$fmsg = "User Registration Failed";
}
}
mysqli_close($connection);
?>
<html>
...
<body>
...
<div>
<form method="POST" class="form-horizontal" role="form">
<!-- Status, how registering went -->
<?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
<?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
<!-- Registration form starts -->
<h2>Form</h2><br>
<label for="Name"></label>
<input name="name" type="text" id="name" maxlength="40" placeholder="Ees- ja perenimi" class="form-control" autofocus> <!-- lopp -->
<label for="email"></label>
<input name="email" type="email" id="email" maxlength="65" placeholder="Email" class="form-control"> <!-- lopp -->
<label for="Username"></label>
<input name="username" type="text" id="userName" maxlength="12" placeholder="Kasutajatunnus/kasutajanimi" class="form-control" required> <!-- lopp -->
<label for="Password"></label>
<input name="password" type="password" id="password" maxlength="12" placeholder="Parool" class="form-control" required>
<button type="submit" class="btn btn-primary btn-block">Join</button>
</form> <!-- /form -->
</div> <!-- ./container -->
...
</body>
</html>
Login:
<?php
session_start();
require ('insert.php');
//Is username and password typed?
if (isset($_POST['username']) and isset($_POST['password'])){
//Making vars from inputs
$username = $_POST['username'];
$password = $_POST['password'];
//Checking existent of values.
$query = "SELECT * FROM `liikmed`
WHERE username='$username'
and password='$password'";
$result = mysqli_query($connection, $query)
or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
//3.1.2 If values equal, create session.
if ($count == 1){
$_SESSION['username'] = $username;
} else {
//If credentials doesn't match.
$fmsg = "Invalid Login Credentials.";
}
}
//if user logged in, welcome with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hai " . $username . "";
echo "This is the Members Area";
echo "<a href='logout.php'>Logout</a>";
}else{}
?>
<html>
...
<body>
...
<div id="bg"></div>
<form method="POST" class="form-horizontal">
<h2>Login</h2><br>
<label for="User"></label>
<input name="username" type="text" maxlength="15" placeholder="Username" class="form-control" required autofocus>
<label for="Password"></label>
<input name="password" type="password" maxlength="50" placeholder="Password" class="form-control" required autofocus>
<button type="submit" class="btn btn-primary btn-block">Enter</button>
</form>
</div>
...
</body>
</html>
And finally php database connection file (called insert.php):
<?php
$connection=mysqli_connect("localhost","root","pw");
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'my_database');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
?>
First of all in your login PHP code, you only started a session but you didn't tell the from where to direct to if login is successful. Add a header to the code. That is;
if ($count == 1){
$_SESSION['username'] = $username;
header("Location: page.php"); //the page you want it to go to
}
And your registration PHP code looks ok. Check your database table if you've misspelt anything there.
Your logic to set the $_SESSION['username'] requires that the username and password combination exists once in your database.
This might sound silly but can you confirm that this is the case (i.e. confirm that you have not created the same username and password combination).
Altering the logic to be > 1 would also get around this temporarily. So your code
if ($count == 1){
$_SESSION['username'] = $username;
}
should become
if ($count > 1){
$_SESSION['username'] = $username;
}
i'm trying to make the sign in and the sign up within the same page in a website i have this form in html
<form name="form1" action="check_login.php" method="post">
<input type="email" id= "email" name="email" required="required" placeholder="Email Address" />
<input type="password" id= "password" name="password" required="required" placeholder="Password"/>
<span><input type="checkbox" class="checkbox">Keep me signed in</span>
<button name="login" type="submit" class="btn btn-default">Login</button>
</form>
and the form
<form name="form2" action="check_login.php" method="post">
<input type="text" id= "fname" name="fname" required="required" placeholder="First Name"/>
<input type="text" id= "mname" name="mname" required="required" placeholder="Middle Name"/>
<input type="text" id= "lname" name="lname" required="required"placeholder="Last Name"/>
<input type="email" id= "email" name="nemail"required="required" placeholder="Email "/>
<input type="password" id= "password" name="npassword"required="required" placeholder="Password"/>
<input type="password" id= "cpassword" name="cpassword"required="required"placeholder="Confirm Password"/>
<select name='gender' class='col-sm-4'>
<option value='male'>male</option>
<option value='female'>female</option>
</select>
<div class='col-sm-offset-8'>
<button name="sign_up" type="submit" class="btn btn-default">Sign up</button> </div>
</form>
they are in the same page and both navigate to other page within my website then i have this code in php
if (!empty($_POST['login']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$sql_stmt="select email, password from users where email = '"
.$email."' and password ='".$password."'";
$result= mysqli_query($connection,$sql_stmt);
if ($result)
{
header ("location: index.php");
}
else {
header ("location: login.php");
}
}
if(!empty($_POST['sign_up']))
{
$fname=$_POST['fname'];
$mname=$_POST['mname'];
$lname=$_POST['lname'];
$gender=$_POST['gender'];
$nemail=$_POST['nemail'];
$npassword=$_POST['npassword'];
//if email is already stored ?
$signup="INSERT INTO `users`(`first_name`, `middle_name`, `last_name`,"
. " `gender`, `email`, `password`)"
. " VALUES ('".$fname."','".$mname."','".$lname."','".$gender.
"','".$nemail."','".$npassword."')";
$result1= mysqli_query($connection, $signup);
if ($result1)
{
header ("location: index.php");
}
else {
header ("location: login.php");
}
}
but the navigation to the index never happen!
First things first you need to validate your user input before storing in the db and also you need to hash your passwords, you can read more about hashing here and also read the FAQ here
Also read about prepared statements whether u use MySQLi or pdo read here :
<?php
if (isset($_POST['login'])) {
$email = userInput($_POST['email']);
$password = userInput($_POST['password']); // verify your password you can learn
$sql_stmt = $connection->prepare("SELECT email,password FROM users where email =? ");
$sql_stmt->bindValue(1, $email);
$sql_stmt->execute();
$results = $sql_stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results > 0 && password_verify($password, $results['password']))) {
$_SESSION['username'] = $results['email'];
header("location:page"); //Login details are correct redirect to page after correct
} else { //email and password do not match
//Return your error message
}
}
if (isset($_POST['sign_up'])) {
$fname = userInput($_POST['fname']);
$mname = userInput($_POST['mname']);
$lname = userInput($_POST['lname']);
$gender = userInput($_POST['gender']);
$nemail = userInput($_POST['nemail']);
$npassword = userInput(password_hash($_POST['npassword'], PASSWORD_DEFAULT));
// check if email already stored/
$sql_stmt = $connection->prepare("SELECT email from users where email = ?");
$sql_stmt->bindValue(1, $nemail);
$sql_stmt->execute();
$results = $sql_stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) {
//Email exist print message
} else {
//email does not exist register the user
$sql_stmt = $connection->prepare("INSERT INTO users (first_name, middle_name, last_name,gender, email, password) value(?,?,?,?,?,?) ");
$sql_stmt->execute(array(
1 => $fname,
2 => $mname,
3 => $last_name,
4 => $gender,
5 => $nemail,
6 => $npassword
));
//Print succcess message;
header(); // redirect where u want
}
}
function userInput($data)
{
$data = trim($data);
$data = stripcslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>