How do i style PHP validations - php

This my first time using PHP validation and my validations are working perfectly.
How do i style the validation, do i select the echo function or do i have to change my validation code to be able to style it. I have tried using a span and echoing out a error function and changing the echo's to the error function e.g $emailErr but not luck, the validations does not work. any suggestions?
HTML
<!-- <div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value='' required><!--<span class="error"><!--<?php //echo $c_emailErr; ?></span>-->
<br>
<figure>
<input class ="login-field" type="password" id="pass1" name="pass1" value="" placeholder="Password" maxlength="30" required><!--<span class="error"><1--<?php //echo $c_pass1Err; ?></span>-->
<input class ="login-field" type="password" id="pass2" name="pass2" value="" placeholder=" Confirm password" maxlength="30" required><!--<span class="error"><!--<?php //echo $c_pass2Err; ?></span>-->
<div id="messages"></div>
</figure>
<p class="remember_me">
</p>
<input type="submit" name="submit" value="Register" id="submit_button" class="btn btn-default">
<br>
</form>
PHP
<?php
if (isset($_POST['submit'])) {
$reg_errors = array();
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];
$emailErr = $pass1Err = $pass2Err = "";
// $c_email = $c_pass1 = $c_pass2 = "";
// Remove all illegal characters from email
// $c_email = filter_var($c_email, FILTER_SANITIZE_EMAIL);
//Checking the email address
if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false) {
echo("<b> This is a valid email address </b>");
} else {
echo("<b> Email is not a valid email address</b>");
}
if (strlen($c_pass1) <= '8') {
echo "<b>Your Password Must Contain At Least 8 Characters!</br>";
//check passwords
}elseif ($c_pass1 == $c_pass2) {
$q = "INSERT INTO Cus_Register(Cus_Email,Cus_Password,Cus_confirm_password) VALUES (?,?,?)";
$stmt = mysqli_prepare($dbc, $q);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $c_email, $c_pass1, $c_pass2);
if ($q) {
echo "<script> alert('registration sucessful')</script>";
}
} else {
echo "<b>Oops! Your passwords do not </b>";
}
}
?>

say you had tag for text and you have the code
<?
echo '<t>this is some text';
?>
to add styles all you simply have to do is style the "t" tag like so in css
t{
font-size:3px;
background-color:red;
// other styles
}

Related

how to show php validations error on page

I have a form and all the validations, now I want to show the error messages in front of the text field not in the url. How do I do this?
Here is my PHP code:
<?php
if ((isset($_POST['submit']))){
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$fullname_valid = $email_valid = $username_valid = $password_valid = false;
if(!empty($fullname)){
if (strlen($fullname) > 2 && strlen($fullname)<=30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
}else {$fmsg .="fullname can contain only alphabets <br>";}
}else{$fmsg1 .="fullname must be 2 to 30 char long <br>";}
}else{$fmsg2 .="fullname can not be blank <br>";}
if (!empty($email)) {
if (filter_var($email , FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con,$query2) or die("can not fire query".mysqli_error($con));
if (mysqli_num_rows($fire2)>0) {
$msg .=$email."is already taken please try another one<br> ";
}else{
$email_valid=true;
}
# code...
}else{$msg .=$email."is an invalid email address <br> ";}
# code...
}else{$msg .="email can not be blank <br>";}
if(!empty($username)){
if (strlen($username) > 4 && strlen($username)<=15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con,$query) or die("can not fire query".mysqli_error($con));
if(mysqli_num_rows($fire)> 0){
$umsg ='<p style="color:#cc0000;">username already taken</p>';
}else{
$username_valid = true;
}
# code...
# code...
}else {$msg.= "username can contain only alphabets <br>";}
}else{$msg.= "username must be 4 to 15 char long <br>";}
}else{$msg.="username can not be blank <br>";}
if (!empty($password)) {
if (strlen($password) >=5 && strlen($password) <= 15 ) {
$password_valid = true;
$password = md5($password);
# code...
}else{$msg .= $password."password must be between 5 to 15 character long<br>";}
# code...
}else{$msg .= "password can not be blank <br>";}
if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con,$query) or die ("can not insert data into database".mysqli_error($con));
if ($fire){
header("Location: dashboard.php");}
}else{
header("Location: createaccount.php?msg=".$msg);
}
}
?>
and this is my html code:
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<div class="form-input">
<input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">
</div>
<input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">
<span id="message"></span>
<div class="form-input">
<input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
</div>
<div>
<input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
</div>
<div>
<input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
</div>
<div>
<input type="submit" name="submit" id="submit"
value="sign up" class="btn btn-primary btn-block">
forgot password?
<h3>have an account? log in</h3>
</div>
</form>
How do I get the error message in front of my text field, and also how do I get the specified error in front of the specified text field? I don't want to use ajax or javascript. I want to do it with PHP. I have tried this but no luck.
<?php if(isset($errorfname)) { echo $errorfname; } ?>
send msg to get params is not good idea.
Use session
$_SESSION['error_msg'] = $msg
header("Location: createaccount.php");
and add get error in php
$errors = '';
if(isset($_SESSION['error_msg'])) { $errors = $_SESSION['error_msg']; } ?>
and in html show $errors
By looking at your form does not have an action attribute therefore one can concluded that you are submitting the form at the same page as the form PHP_SELF
So if you want to display the error next to the field I would advice that you first declare an empty variables for each text error on top of your page then echo the variables next to each field.
<?php
$emailError = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$errors = 0;
if ((isset($_POST['submit']))) {
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$fullname_valid = $email_valid = $username_valid = $password_valid = false;
if (!empty($fullname)) {
if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
} else {
$fullnameError = "fullname can contain only alphabets <br>";
$errors++;
}
} else {
$fullnameError = "fullname must be 2 to 30 char long <br>";
$errors++;
}
} else {
$fullnameError = "fullname can not be blank <br>";
$errors++;
}
if (!empty($email)) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con, $query2) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire2) > 0) {
$emailError = $email . "is already taken please try another one<br> ";
} else {
$email_valid = true;
}
# code...
} else {
$emailError = $email . "is an invalid email address <br> ";
$errors++;
}
# code...
} else {
$emailError = "email can not be blank <br>";
}
if (!empty($username)) {
if (strlen($username) > 4 && strlen($username) <= 15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con, $query) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire) > 0) {
$usernameError = '<p style="color:#cc0000;">username already taken</p>';
$errors++;
} else {
$username_valid = true;
}
} else {
$usernameError = "username can contain only alphabets <br>";
$errors++;
}
} else {
$usernameError = "username must be 4 to 15 char long <br>";
$errors++;
}
} else {
$usernameError = "username can not be blank <br>";
$errors++;
}
if (!empty($password)) {
if (strlen($password) >= 5 && strlen($password) <= 15) {
$password_valid = true;
$password = md5($password);
# code...
} else {
$passwordError = $password . "password must be between 5 to 15 character long<br>";
$errors++;
}
# code...
} else {
$passwordError = "password can not be blank <br>";
$errors++;
}
//if there's no errors insert into database
if ($errors <= 0) {
if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
if ($fire) {
header("Location: dashboard.php");
}
}
}
}
?>
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<div class="form-input">
<input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">
<!-- display email error here -->
<?php echo $emailError?>
</div>
<input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">
<span id="message"></span>
<div class="form-input">
<input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
<?php echo $fullnameError?>
</div>
<div>
<input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
<?php echo $usernameError?>
</div>
<div>
<input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
<?php echo $passwordError?>
</div>
<div>
<input type="submit" name="submit" id="submit" value="sign up" class="btn btn-primary btn-block">
forgot password?
<h3>have an account? log in</h3>
</div>
</form>
NB: I would advice that you look into password_hash() and
password_verify()to hash your passwords, they provide better
security as compared tomd5()` and make sure your database column is
atleast 60 characters in length.. I would also advice to look into
prepared statements.
The following can help :
How can I prevent SQL injection in PHP?
Using PHP 5.5's password_hash and password_verify function
I think the best way is include from template in result
if ($fire){
header("Location: dashboard.php");
}else{
include("createaccount.php");
}
And in createaccount.php
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<p class="errors"><?= $msg ?></p>
...

php form and validation - form values being returned as empty [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Why does this PDO statement silently fail?
(2 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I hope someone can shed some light on this issue. I have created a registration form that submits to a second page for validation. there are various checks to catch errors and unwanted user input and is failing on checking for empty fields.. even if all the fields have data in them, it is still being returned as empty
here is my form - note it does include a hidden field to which it was suggested to use a /> instead of the usual > tag - either way makes no difference
<form id="registersocial" class="SRF" name="registersocial" action="php.includes/rasocial.inc.php" method="POST">
<div id="formheaders"><strong>Personal Details</strong></div>
<br/>
<fieldset>
<lable><strong>First Name</strong><br/>
<input type="text" name="firstname" id="firstname" class="SRF" onKeyup="restrict('firstname')" placeholder="First Name" >
<span id="Errmsg-first"></span>
</lable>
<br/>
<lable><strong>Last Name</strong><br/>
<input type="text" name="lastname" id="lastname" class="SRF" onKeyup="restrict('lastname')" placeholder="Last Name" >
<span id="Errmsg-last"></span>
</lable>
<br/>
</fieldset>
<fieldset>
<lable><strong>Date of Birth</strong><br/>
<select name="birthmonth" id="birthmonth" class="SRF">
<?php require("php.includes/month.inc.php"); ?>
</select>
<span id="Errmsg-mob"></span>
<input type="text" name="birthday" id="birthday" class="SRF" maxlength="2" placeholder="Day">
<span id="Errmsg-dob"></span>
<input type="text" name="birthyear" id="birthyear" class="SRF" maxlength="4" placeholder="Year">
<span id="Errmsg-yob"></span>
</lable>
<br/>
</fieldset>
<fieldset>
<lable><strong>Location</strong><br/>
<select name="country" id="country">
<?php require("php.includes/countrylist.php"); ?>
</select>
<span id="Errmsg-country"></span>
</lable>
<br/>
</fieldset>
<hr class="SRF">
<div id="formheaders"><strong >Account Information</strong></div>
<br/>
<fieldset>
<input type="hidden" name="accounttype" id="accounttype" class="SRF" value="Social"/>
<lable><strong>Create a Username</strong><br/>
<input type="text" name="username" id="username" class="SRF" onKeyup="restrict('username')" onblur="checkusername()" placeholder="Username" >
<span id="Errmsg-username"></span>
</lable>
<br/>
<lable><strong>Your Current Email</strong><br/>
<input type="email" name="email" id="email" class="SRF" onKeyup="restrict('email')" placeholder="Your Email" >
<span id="Errmsg-email"></span>
</lable>
<br/>
<lable><strong>Create a Password</strong><br/>
<input type="password" name="pwd" id="pwd" class="SRF" placeholder="Password" >
<span id="Errmsg-password"></span>
</lable>
<br/>
<br/>
<input type="submit" id="submit" name="submit" value="submit">
</fieldset>
<br/>
<span id="status"></span>
<br/>
</form>
below is the file that gets the posted data and runs through validation file name is rasocial.inc.php - again my issue is that upon completing the form, I am getting a empty error in the url - I am sure it is simple but cannot see it for the life of me
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])) {
include_once("ctb.inc.php");
$fn = mysqli_real_escape_string($pdo, $_POST['firstname']);
$ln = mysqli_real_escape_string($pdo, $_POST['lastname']);
$bm = mysqli_real_escape_string($pdo, $_POST['birthmonth']);
$bd = mysqli_real_escape_string($pdo, $_POST['birthday']);
$by = mysqli_real_escape_string($pdo, $_POST['birthyear']);
$co = mysqli_real_escape_string($pdo, $_POST['country']);
$at = mysqli_real_escape_string($pdo, $_POST['accounttype']);
$un = mysqli_real_escape_string($pdo, $_POST['username']);
$em = mysqli_real_escape_string($pdo, $_POST['email']);
$pwd = mysqli_real_escape_string($pdo, $_POST['pwd']);
var_dump($fn, $ln, $bm, $bd, $by, $co, $at, $un, $em, $pwd);
//Error Handlers
//Check for empty fields
if (empty($fn) || empty($ln) || empty($bm) || empty($bd) || empty($by) || empty($co) || empty($at) || empty($un) || empty($em) || empty($pwd)) {
header("Location: ../registersocial.php?registersocial=empty");
exit();
} else {
//Check firstname and lastname for valid chars
if (!preg_match("/^[a-zA-Z]*$/", $fn) || !preg_match("/^[a-zA-Z]*$/", $ln)) {
header("Location: ../registersocial.php?registersocial=invalidcharacters");
exit();
} else {
//Check birth month has been selected
if ($_POST['birthmonth'] == '0') {
header("Location: ../registersocial.php?registersocial=birthmonth");
exit();
} else {
//Check birth day is numbers only
if (!preg_match("/^[0-9]*$/", $bd)) {
header("Location: ../registersocial.php?registersocial=birthday");
exit();
} else {
//Check the birth day length is 2 characters
if (strlen($bd) != 2 ) {
header("Location: ../registersocial.php?registersocial=birthdaylength");
exit();
} else {
//Check birth year is numbers only
if (!preg_match("/^[0-9]*$/", $by)) {
header("Location: ../registersocial.php?registersocial=birthyear");
exit();
} else {
//Check birth year is 4 characters
if (strlen($by) != 4 ) {
header("Location: ../registersocial.php?registersocial=birthyearlength");
exit();
} else {
//Check country has been selected
if ($_POST['country'] == '0') {
header("Location: ../registersocial.php?registersocial=country");
exit();
} else {
//Check if accounttype has been modified
if (!preg_match("/^[a-zA-Z]*$/", $at) || $_POST['accounttype'] != 'Social') {
header("Location: ../registersocial.php?registersocial=accounttype");
exit();
} else {
//Check username isnt taken
if (!preg_match("/^[a-zA-Z0-9]*$", $un)) {
header("Location: ../registersocial.php?registersocial=invalidusername");
exit();
} else {
//Check username is not taken in db
$stmt = $pdo->prepare('SELECT * FROM sh_userdata WHERE username =?');
$stmt->execute($un);
$usernamecheck = $stmt->fetch();
if ($usernamecheck > 0 ) {
header("Location: ../registersocial.php?registersocial=usernametaken");
exit();
} else {
//Check email is valid
if (!filter_var($em, FILTER_VALIDATE_EMAIL) ) {
header("Location: ../registersocial.php?registersocial=invalidemail");
exit();
} else {
//Check if email exists in db
$stmt = $pdo->prepare('SELECT * FROM sh_userdata WHERE email =?');
$stmt->execute($em);
$emailcheck = $stmt->fetch();
if ($emailcheck > 0 ) {
header("Location: ../registersocial.php?registersocial=emailtaken");
exit();
//add dob fields to make date of birth
$dob = new DateTime($by.'-'.$bm.'-'.$bd);
$dob->format('Y-m-d');
//hash password
$hashedpwd = password_hash($pwd, PASSWORD_DEFAULT);
//insert user into db
$stmt = $pdo->prepare("INSERT INTO sh_userdata (username, email, password, accounttype, signupdate, lastlogindate) VALUES (?,?,?,?,NOW(),NOW())");
$stmt->execute(array("$un","$em","$hashedpwd","$at"));
header("Location: ../registersocial.php?registersocial=sucess");
exit();
}
}
}
}
}
}
}
}
}
}
}
}
}
} else {
header("Location: ../registersocial.php?registersocial=nopost");
exit();
}
any help or suggestions would be really appreciated

PHP- Form Validation Errors

This is my first time validating, I am having the hardest time have spent endless hours on this already. I have a registration form that needs to be validated, i have tried 2 scripts for this. The script that works best can be seen below: however every time I try to echo the error message to display under my text field i receive the following error messages:
Notice: Undefined variable: c_email in /Applications/MAMP/htdocs/PhpProject2/Reg_1.php on line 161
Notice: Undefined variable: c_emailErr in /Applications/MAMP/htdocs/PhpProject2/Reg_1.php on line 163
Notice: Undefined variable: c_pass1Err in /Applications/MAMP/htdocs/PhpProject2/Reg_1.php on line 169
C_emailErr and c_pass1Err are both defined.
any help would be appreciated.
HTML
<section class="container">
<form id="myform " class="Form" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" accept-charset="utf-8">
<!--<div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value="<?= $c_email ?>" required >
<br>
<span class="error"><?php echo $c_emailErr; ?></span>
<br>
<figure>
<input class ="login-field" type="password" id="pass1" name="pass1" value="<?= $c_pass1 ?>" placeholder="Password" maxlength="30" required>
<br>
<span class="error"><?php echo $c_pass1Err; ?></span>
<br>
<input class ="login-field" type="password" id="pass2" name="pass2" value="" placeholder=" Confirm password" maxlength="30" required><!--<span class="error"><?php //echo $c_pass2Err; ?></span>-->
<div id="messages"></div>
</figure>
<p class="remember_me">
</p>
<input type="submit" name="submit" value="Register" id="submit_button" class="btn btn-default">
<br>
</form>
<?php
?>
</form>
</section>
PHP
<?php
if (isset($_POST['submit'])) {
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];
$c_emailErr = $c_pass1Err = $c_pass2Err = "";
//Checking the email address
if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false) {
echo ("<b id='email'> This is a valid email address </b>");
} else {
echo ("<b id='email'> Email is not a valid email address</b>");
}
if (strlen($c_pass1) <= '8') {
echo "<b>Your Password Must Contain At Least 8 Characters!</br>";
//check passwords
} elseif ($c_pass1 == $c_pass2) {
$q = "INSERT INTO Cus_Register(Cus_Email,Cus_Password,Cus_confirm_password) VALUES (?,?,?)";
$stmt = mysqli_prepare($dbc, $q);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $c_email, $c_pass1, $c_pass2);
if ($q) {
echo "<script> alert('registration sucessful')</script>";
}
} else {
echo "<b>Oops! Your passwords do not </b>";
}
}
?>
You are defining those variables, but you are defining them inside of an if block.. Move them outside of the if block.
<?php
$c_emailErr = $c_pass1Err = $c_pass2Err = "";
if (isset($_POST['submit'])) {
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];

php- login validations not working

This is my first time validating a form.
I have got stuck on validating the email in theory it seems like it should work but it doesn't.
The following code only works when i remove the email validation:
if ($c_pass1 == $c_pass2) {
} else {
echo "Oops! Your passwords do not match ";
not to sure where i have gone wrong. The validation literally does nothing. is there a better way to validate an email address?
HTML
<!-- <div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value='' required><!--<span class="error"><?php //echo $c_emailErr; ?></span>-->
<br>
<figure>
<input class ="login-field" type="password" id="pass1" name="pass1" value="" placeholder="Password" maxlength="30" required><!--<span class="error"><?php //echo $c_pass1Err; ?></span>-->
<input class ="login-field" type="password" id="pass2" name="pass2" value="" placeholder=" Confirm password" maxlength="30" required><!--<span class="error"><?php //echo $c_pass2Err; ?></span>-->
<div id="messages"></div>
</figure>
<p class="remember_me">
</p>
<input type="submit" name="submit" value="Register" id="submit_button" class="btn btn-default">
<br>
</form>
PHP
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];
$c_emailErr = $c_pass1Err = $c_pass2Err = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//Validates email
if (empty($_POST["email"])) {
$c_emailErr = "You Forgot to Enter Your Email!";
} else {
$c_email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$c_emailErr )) {
$c_emailErr = "You Entered An Invalid Email Format";
}
}
if ($c_pass1 == $c_pass2) {
$q = "INSERT INTO Cus_Register(Cus_Email,Cus_Password,Cus_confirm_password) VALUES (?,?,?)";
$stmt = mysqli_prepare($dbc, $q);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $c_email, $c_pass1, $c_pass2);
if ($q) {
echo "<script> alert('registration sucessful')</script>";
}
} else {
echo "<b>Oops! Your passwords do not </b>";
}
}
}
?>
To validate Email Instead Of doing this: if (empty($_POST["email"])) { Try doing this if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false
That should take care of the email part
Now for the password part try this:
if ($_POST[$c_pass1 != $c_pass2]) {echo'wrong password';}else{echo 'good password';}

How to add session to an HTML log in form

I'm working on an HTML form, which is connected to MySQL database. Database is updating with new data every time, when I reload the page and also when a failed submit occur.
This is my code, Anyone please help me to add session to this page and please give me a solution
<body>
<?php
// define variables and set to empty values
$email_id = $first_name = $last_name = $district = $city = $address = $mobile_no = $password = "";
$email_idErr = $first_nameErr = $last_nameErr = $districtErr = $cityErr = $addressErr = $mobile_noErr = $passwordErr = "";
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//First name validation
if(empty($_POST["first_name"]))
{$first_nameErr="First name is required";}
else
{$first_name = test_input($_POST["first_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$first_name))
{$first_nameErr="Only letters and white spaces allowed";}
}
//Second name validation
if(empty($_POST["last_name"]))
{$last_nameErr="Last name is required";}
else
{$last_name = test_input($_POST["last_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$last_name))
{$last_nameErr="Only letters and white spaces allowed";}
}
//E-mail validation
if(empty($_POST["email_id"]))
{$email_idErr="E-mail id is required";}
else
{$email_id = test_input($_POST["email_id"]);
//checking email format
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email_id))
{$email_idErr="Invalid email format";}
}
//District is required
if(empty($_POST["district"]))
{ $districtErr="District is required";}
else
{ $district = test_input($_POST["district"]);
if(!preg_match("/^[a-zA-Z]*$/",$district))
{$districtErr="Only letters and white spaces allowed";}
}
$city = test_input($_POST["city"]);
$address = test_input($_POST["address"]);
//Mobile number validation
if(empty($_POST["mobile_no"]))
{$mobile_noErr="Mobile number is required";}
else
{$mobile_no = test_input($_POST["mobile_no"]);
if(!preg_match("/^[0-9]*$/",$mobile_no))
{$mobile_noErr="Invalid Mobile number";}
}
//Password validation
if(empty($_POST["password"]))
{$passwordErr="Password is required";}
else
{ $password = test_input($_POST["password"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
$con=mysqli_connect("localhost","root","","ashlyn");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{echo "Connection Established";}
$sql="INSERT INTO user_details (email_id, first_name, last_name, district, city, address, mobile_no, password)
VALUES ('$email_id', '$first_name', '$last_name', '$district', '$city', '$address', '$mobile_no', '$password')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "You are successfully registered..";
mysqli_close($con);
?>
<section class="container">
<div class="login">
<h1>User Login Page</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);>">
<p><input type="text" name="first_name" value="" placeholder="First Name"><span class="error">* <?php echo $first_nameErr;?></span></p>
<p><input type="text" name="last_name" value="" placeholder="Last Name"> <span class="error">* <?php echo $last_nameErr;?></span>
</p>
<p><input type="text" name="email_id" value="" placeholder="Email"><span class="error">* <?php echo $email_idErr;?></span>
</p>
<p><input type="text" name="district" value="" placeholder="District"><span class="error">* <?php echo $districtErr;?></span></p>
<p><input type="text" name="city" value="" placeholder="City">
</p>
<p><input type="text" name="address" value="" placeholder="Address">
</p>
<p><input type="text" name="mobile_no" value="" placeholder="Mobile Number"> <span class="error">* <?php echo $mobile_noErr;?></span>
</p>
<p><input type="password" name="password" value="" placeholder="Password"> <span class="error">* <?php echo $passwordErr;?></span>
</p>
<p class="submit"><input type="submit" name="submit" value="Submit"></p>
</form>
what you need is
<?php session_start();
on the first line bevor any output
https://stackoverflow.com/a/8084900/1792420

Categories