Not being able to verify password SQL - javascript

Update: After someone suggested in comments it's working now. I am still not able to work the login/logout button that's in index.php file. When I log in it does verify the password, but does not show the logout button. It shows the error in index.php (I have commented out the line) it says undefined index name Any help is appreicated.
I have a signup and login form in my website. I am able to signup properly and I am storing the password as hashed. When I try to login it keep saying wrong password. I am assuming there might be something wrong with my code since the password I am typing is correct.
index.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
require "navigationbar.php";
require "loginpage.php";
?>
<html>
<head>
<link href="https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap" rel="stylesheet">
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
<link href="stylee.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght#100&display=swap" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<?php
$user = $_SESSION['name'] ; //it says undefined index name
if (isset($user )) {
echo '<p>You are logged in</p>';
echo '<form action="logout.php" method="post">
<button type="submit" name="logout-submit">Logout</button>
</form>';
<link href="stylee.css" rel="stylesheet" />
<form action="logoutbackend.php" method="post">
<button type="submit" name="logout-submit" class="logout_button">Logout</button>
</form>';
} else {
echo '<p class="login-status">You are logged out!</p>';
echo '<div class="login-container">
<form action="./backend/loginbackend.php" method="post">
<div class="form-group row">
<div class="col-sm-10">
<h2>website</h2>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="email" class="form-control" name="email" placeholder="Email">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10" >
<input type="password" class="form-control" name="password" placeholder="password">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary" name="login_submit">Log In</button>
</div>
</div>
</form>
<div class="form-group row">
<div class="col-sm-10">
<p>New to <span>ShowCo</span>?<a class="open-button" onclick="openForm()">Sign up</a> </p>
</div>
</div>
<div class="form-popup" id="myForm">
<form action="./backend/signupbackend.php" class="form-container" method="post">
<div class="form-group row">
<div class="col-sm-10" >
<h1>Sign up</h1>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10" >
<input type="text" class="form-control" placeholder="Username" name="username" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10" >
<input type="email"class="form-control" placeholder="Email address" name="mail" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10" >
<input type="password" class="form-control" placeholder="Password" name="password" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10" >
<input type="password" class="form-control" placeholder="Repeat password" name="repeatpassword" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10" >
<button type="submit" class="btn btn-primary" name="signup_submit">Sign up</button>
</div>
</div>
<button type="button" class="close" aria-label="Close" onclick="closeForm()"><span aria-hidden="true">×</span></button>
</form>
</div>
</div>
<script>
function openForm() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
</script>
';
}
?>
</body>
</html>
<?php
require "footer.php";
?>
Signupbackend.php
<?php
if(isset($_POST["signup_submit"])) {
require "../database_files/database_for_signup.php";
require "../index.php";
$username = $_POST['username'];
$email = $_POST['mail'];
$password = $_POST['password'];
$repeatPassword = $_POST['repeatpassword'];
if (empty($username) || empty($email) || empty($password) || empty($repeatPassword)) {
header("Location: ../index.php?error=emptyfields&username=" .$username."&mail=" .$email);
exit();
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/",$username)) {
header("Location: ../index.php?error=invalidmailusername");
exit();
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../index.php?error=invalidmail&username=".$username);
exit();
} else if (!preg_match("/^[a-zA-Z0-9]*$/",$username)) {
header("Location: ../index.php?error=invalidusername&mail=".$email);
exit();
} else if($password != $repeatPassword) {
header("Location: ../index.php?error=passwordcheck&username=".$username."&mail=".$email);
exit();
} else {
$sql = "SELECT COUNT(username) AS num FROM signup_info WHERE username = :username";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['num'] > 0) {
die('Sorry, username already exists. Please try a different username');
}
$passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
$sql = "INSERT INTO signup_info(username, email, password) VALUES (:username, :email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':password', $passwordHash);
$result = $stmt->execute();
if($result) {
echo "Registered!";
}
}
}
?>
Loginbackend.php
<?php
if(isset($_POST['login_submit'])) {
require "../database_files/database_for_signup.php";
$email = $_POST['email'];
$password = $_POST['password'];
if ((empty($username)) || (empty($password))) {
echo 'empty username/password';
die();
}
$sql = 'SELECT username, email, password FROM signup_info WHERE email = :email';
if ($stmt = $conn->prepare($sql)) {
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
if ($stmt->execute()) {
if($stmt->rowCount() == 1) {
if ($row = $stmt->fetch()) {
$hashed_password = $row['password'];
if(password_verify($password, $hashed_password)) {
session_start();
$_SESSION['email'] = $email;
$_SESSION['name'] = $row['username'];
echo "verfiied";
} else {
echo "wrong password"; }
}
}
}
}
}
?>
logout.php
<?php
session_start();
session_unset();
session_destroy();
header("Location: ./index.php");
Please help me why I am not able to verify the password? Also, I have been through similar questions on SO, but nothing helped. Any help is appreciated.

Related

How can I redirect users to different pages after inserting into the database using Sweet Alert in PHP?

I am finding it difficult to use the sweet alert after a successful login and also add the sweet alert after a user successfully inserts his/her data into the database. I am finding it difficult to use the sweet alert after a successful login and also add the sweet alert after a user successfully inserts his/her data into the database.x
<?php
include ("dbcon.php");
session_start();
if(isset($_POST['login'])){
//get the user data
$username = mysqli_real_escape_string($conn , $_POST['username']);
$email = mysqli_real_escape_string($conn , $_POST['email']);
$pwd = mysqli_real_escape_string($conn , $_POST['pdf]);
if(empty($username) || empty($email) || empty($pwd)){
header("Location:../../login.php?loginempty");
exit();
}else{
$select = "SELECT * FROM users WHERE email ='$email' ";
$result = mysqli_query($conn , $select);
$result_check = mysqli_num_rows($result);
if($result_check < 1){
header("Location:../../login.php?invaliduid");
exit();
}else{
if($row=mysqli_fetch_assoc($result)){
$cpwd = $row['pwd'];
//de-hashed the password
// $hashedpwd = password_verify($pwd, $row['pdf]);
if($pwd != $cpwd){
header("Location: ../../login.php?invalidpwd");
exit();
}elseif($pwd == $cpwd){
$_SESSION['uid'] =$row['username'];
$username = $_SESSION['uid'];
echo "
Swal.fire({
title: 'Welcome to bottles beach',
text: 'You successfully submitted the form,
icon: 'success',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Great, show me the site!'
}).then((result) => {
if (result.confirmed) {
location = '../../dashboard.php'
}
})
";
// header("Location:../../dashboard.php?loginsuc");
// exit();
}
}
}
}
}
?>
<?php
session_start();
include ("dbcon.php");
if(isset($_POST["reg-btn"])) {
$username = mysqli_real_escape_string($conn , $_POST['username']);
$email = mysqli_real_escape_string($conn , $_POST['email']);
$phone = mysqli_real_escape_string($conn , $_POST['phone']);
$pwd = mysqli_real_escape_string($conn , $_POST['pwd']);
$cpwd = mysqli_real_escape_string($conn , $_POST['cpwd']);
// $verify_token = md5(random());
// VALIDATION
if(strlen(trim($pwd)) < 5) {
// Password Length
header("Location:../../register.php?passwordshort");
exit();
}
if($pwd != $cpwd ) {
// If Password = Confirm Password
header("Location:../../register.php?comfirmpass");
exit();
}
// Check for Empty Inputs
if (empty($username)|| empty($email)|| empty($phone)|| empty($pwd)|| empty($cpwd) ) {
header ("Location:../../register.php?signupempty");
exit();
}else {
//VALIDATE EMAIL
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
header ("Location:../../register.php?invalidemail");
exit();
}else {
$select = "SELECT * FROM users WHERE username = '$username' AND pwd ='$pwd'";
$result = mysqli_query($conn , $select);
$result_check = mysqli_num_rows($result);
if($result_check > 0) {
echo "ooooops!!! user already exists";
}else {
$insert = "INSERT INTO users (username, email, phone, pwd, cpwd) VALUES ('$username', '$email', '$phone', '$pwd', '$cpwd')";
$result = mysqli_query($conn , $insert);
if(!$result) {
echo "ooooops!!! an error was encountered while inserting data to the database";
}else {
echo "
Swal.fire({
title: 'Welcome to bottles beach',
text: 'You successfully submitted the form,
icon: 'success',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Great, show me the site!'
}).then((result) => {
if (result.confirmed) {
location = '../../login.php'
}
})
";
// header("location: ../../login.php");
// exit();
}
}
}
}
}else {
header ("Location:../../register.php?signupempty");
exit();
}
?>
<?php
$page_title = "Login Form";
include ('assets/includes/header.php');
include ('assets/includes/navbar.php');
?>
<div class="py-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card shadow">
<div class="card-header">
<h5>Login Form</h5>
</div>
<div class="card-body">
<form action="assets/action/login_action.php" method="POST" autocomplete="no">
<div class="form-group mb-3">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" autocomplete="off">
</div>
<div class="form-group mb-3">
<label for="email">Email</label>
<input type="email" name="email" id="email" class="form-control" autocomplete="off">
</div>
<div class="form-group mb-3">
<label for="pwd">Password</label>
<input type="text" name="pwd" id="pwd" class="form-control" autocomplete="off">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" name="login">Login Now</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
include ('assets/includes/footer.php');
?>
<?php
$page_title = "Registration Form";
include ('assets/includes/header.php');
include ('assets/includes/navbar.php');
// include ('assets/action/dbcon.php');
?>
<div class="py-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card shadow">
<div class="card-header">
<h5>Registration Form With Email Verification</h5>
</div>
<div class="card-body">
<form action="assets/action/code.php" method="POST">
<div class="form-group mb-3">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" autocomplete="off">
</div>
<div class="form-group mb-3">
<label for="email">Email</label>
<input type="email" name="email" id="email" class="form-control" autocomplete="off">
</div>
<div class="form-group mb-3">
<label for="phone">Phone Number</label>
<input type="text" name="phone" id="phone" class="form-control" autocomplete="off">
</div>
<div class="form-group mb-3">
<label for="pwd">Password</label>
<input type="text" name="pwd" id="pwd" class="form-control" autocomplete="off">
</div>
<div class="form-group mb-3">
<label for="cpwd">Confirm Password</label>
<input type="text" name="cpwd" id="cpwd" class="form-control" autocomplete="off">
</div>
<div class="form-group">
<button type="submit" name="reg-btn" class="btn btn-primary">Register Now</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
include ('assets/includes/footer.php');
?>
difficult adding sweet alert redirection after a user successfully inserts his / her details
<button type="submit" class="btn btn-primary" name="login">Login Now</button>
try to use javascript code on button click.
<script>
$(document).ready(function()
{
$("#login").click(function()
{
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "check.php", <--- //your php code for checking credentials
data: {username:username, password:password},
cache: false,
success: function(data){
swal({
title: "Success!",
text: "Login Successfully!",
type: "success"
});
window.location.href = "dashboard.php"; <--your link to next page
},
error: function(xhr, status, error) {console.error(xhr);}
});
});
});
</script>

Form Data is not getting stored in database

I have Two new fields here:
Its Number & Mauze but I am unable to see data in database:
The form gets submitted successfully but i cannot find the values of these two fields in my database
here's my code:
For form fields:
<div class="col-md-6">
<!-- custom text field -->
<label for='its' class="mycss1"><?php esc_html_e('ITS Number', 'masterstudy-lms-learning-management-system'); ?></label>
<input type="text"
name="its"
placeholder="Enter your ITS Number"
class="mycss"
kr-icon="fas fa-envelope"
required/>
</div>
<div class="col-md-6">
<!-- custom text field -->
<label for='mauze' class="mycss1"><?php esc_html_e('Enter your Mauze', 'masterstudy-lms-learning-management-system'); ?></label>
<input type="text"
name="mauze"
placeholder="Mauze"
class="mycss"
kr-icon="fas fa-envelope"
required/>
</div>`
for database connection:
<?php
if (isset($_POST['register'])) {
extract($_POST);
$servername = "localhost ";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `wp_usermeta` (its,mauze)
VALUES ('$its','$mazue')";
if ($conn->query($sql) === TRUE) {
header('Location: register.php');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
Here's my full form data its an signup form
<?php
stm_lms_register_style('register');
enqueue_register_script();
$r_enabled = STM_LMS_Helpers::g_recaptcha_enabled();
$disable_instructor = STM_LMS_Options::get_option('register_as_instructor', false);
if ($r_enabled):
$recaptcha = STM_LMS_Helpers::g_recaptcha_keys();
endif;
$site_key = (!empty($recaptcha['public'])) ? $recaptcha['public'] : '';
if (class_exists('STM_LMS_Form_Builder')):
$additional_forms = STM_LMS_Form_Builder::register_form_fields();
$default_fields = STM_LMS_Form_Builder::profile_default_fields_for_register();
$register_form = $additional_forms['register'];
$become_instructor = $additional_forms['become_instructor'];
?>
<script>
window.profileDefaultFieldsForRegister = <?php echo sanitize_text_field(json_encode($default_fields)); ?>;
window.additionalRegisterFields = <?php echo sanitize_text_field(json_encode($register_form)); ?>;
window.additionalInstructorsFields = <?php echo sanitize_text_field(json_encode($become_instructor)); ?>;
</script>
<?php
endif;
?>
<div id="stm-lms-register"
class="vue_is_disabled"
v-init="site_key = '<?php echo stm_lms_filtered_output($site_key); ?>'"
v-bind:class="{'is_vue_loaded' : vue_loaded}">
<h3><?php esc_html_e('Sign Up', 'masterstudy-lms-learning-management-system'); ?></h3>
<form #submit.prevent="register()" class="stm_lms_register_wrapper">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="heading_font"><?php esc_html_e('Username', 'masterstudy-lms-learning-management-system'); ?></label>
<input class="form-control"
type="text"
name="login"
v-model="login"
placeholder="<?php esc_html_e('Enter username', 'masterstudy-lms-learning-management-system'); ?>"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="heading_font"><?php esc_html_e('E-mail', 'masterstudy-lms-learning-management-system'); ?></label>
<input class="form-control"
type="email"
name="email"
v-model="email"
placeholder="<?php esc_html_e('Enter your E-mail', 'masterstudy-lms-learning-management-system'); ?>"/>
</div>
</div>
<div class="col-md-6">
<!-- custom text field -->
<label for='its' class="mycss1"><?php esc_html_e('ITS Number', 'masterstudy-lms-learning-management-system'); ?></label>
<input type="text"
name="its"
placeholder="Enter your ITS Number"
class="mycss"
kr-icon="fas fa-envelope"
required/>
</div>
<div class="col-md-6">
<!-- custom text field -->
<label for='mauze' class="mycss1"><?php esc_html_e('Enter your Mauze', 'masterstudy-lms-learning-management-system'); ?></label>
<input type="text"
name="mauze"
placeholder="Mauze"
class="mycss"
kr-icon="fas fa-envelope"
required/>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="heading_font"><?php esc_html_e('Password', 'masterstudy-lms-learning-management-system'); ?></label>
<input class="form-control"
type="password"
name="password"
v-model="password"
placeholder="<?php esc_html_e('Enter password', 'masterstudy-lms-learning-management-system'); ?>"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="heading_font"><?php esc_html_e('Password again', 'masterstudy-lms-learning-management-system'); ?></label>
<input class="form-control"
type="password"
name="password_re"
v-model="password_re"
placeholder="<?php esc_html_e('Confirm password', 'masterstudy-lms-learning-management-system'); ?>"/>
</div>
</div>
<div v-for="(profileField, index) in profileDefaultFieldsForRegister" class="col-md-12">
<div class="form-group">
<label class="heading_font" v-html="profileField.label"></label>
<input class="form-control" v-if="index !== 'description'" type="text" v-model="profileField.value" :placeholder="profileField.placeholder" :required="profileField.required" />
<textarea class="form-control" v-if="index === 'description'" v-model="profileField.value" :placeholder="profileField.placeholder" :required="profileField.required"></textarea>
</div>
</div>
</div>
<div class="row additional-fields" v-if="additionalRegisterFields.length"
v-for="(field, index) in additionalRegisterFields">
<div class="col-md-12">
<div class="form-group">
<label class="heading_font" v-if="typeof field.label !== 'undefined'" v-html="field.label"></label>
<?php STM_LMS_Templates::show_lms_template('account/v1/form_builder/email'); ?>
<?php STM_LMS_Templates::show_lms_template('account/v1/form_builder/select'); ?>
<?php STM_LMS_Templates::show_lms_template('account/v1/form_builder/radio'); ?>
<?php STM_LMS_Templates::show_lms_template('account/v1/form_builder/textarea'); ?>
<?php STM_LMS_Templates::show_lms_template('account/v1/form_builder/checkbox'); ?>
<?php STM_LMS_Templates::show_lms_template('account/v1/form_builder/file', array('name' => 'register')); ?>
<div class="field-description" v-if="field.description" v-html="field.description"></div>
</div>
</div>
</div>
<transition name="slide-fade">
<div class="row" v-if="become_instructor && !additionalInstructorsFields.length">
<div class="col-md-6">
<div class="form-group">
<label class="heading_font"><?php esc_html_e('Degree', 'masterstudy-lms-learning-management-system'); ?></label>
<input class="form-control"
type="text"
name="degree"
v-model="degree"
placeholder="<?php esc_html_e('Enter Your Degree', 'masterstudy-lms-learning-management-system'); ?>"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="heading_font"><?php esc_html_e('Expertise', 'masterstudy-lms-learning-management-system'); ?></label>
<input class="form-control"
type="text"
name="expertize"
v-model="expertize"
placeholder="<?php esc_html_e('Enter your Expertize', 'masterstudy-lms-learning-management-system'); ?>"/>
</div>
</div>
</div>
</transition>
<div class="row additional-fields" v-if="become_instructor && additionalInstructorsFields.length"
v-for="(field, index) in additionalInstructorsFields">
<div class="col-md-12">
<div class="form-group">
<label class="heading_font" v-if="typeof field.label !== 'undefined'" v-html="field.label"></label>
<?php STM_LMS_Templates::show_lms_template('account/v1/form_builder/email'); ?>
<?php STM_LMS_Templates::show_lms_template('account/v1/form_builder/select'); ?>
<?php STM_LMS_Templates::show_lms_template('account/v1/form_builder/radio'); ?>
<?php STM_LMS_Templates::show_lms_template('account/v1/form_builder/textarea'); ?>
<?php STM_LMS_Templates::show_lms_template('account/v1/form_builder/checkbox'); ?>
<?php STM_LMS_Templates::show_lms_template('account/v1/form_builder/file', array('name' => 'becomeInstructor')); ?>
<div class="field-description" v-if="field.description" v-html="field.description"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<?php STM_LMS_Templates::show_lms_template('gdpr/privacy_policy'); ?>
<?php do_action('stm_lms_register_custom_fields'); ?>
<div class="stm_lms_register_wrapper__actions">
<?php ?>
<?php if (!$disable_instructor): ?>
<label class="stm_lms_styled_checkbox">
<span class="stm_lms_styled_checkbox__inner">
<input type="checkbox"
name="become_instructor"
v-model="become_instructor"/>
<span><i class="fa fa-check"></i> </span>
</span>
<span><?php esc_html_e('Register as Instructor', 'masterstudy-lms-learning-management-system'); ?></span>
</label>
<?php endif; ?>
<button type="submit"
class="btn btn-default"
:disabled="loading"
v-bind:class="{'loading': loading}">
<span><?php esc_html_e('Register', 'masterstudy-lms-learning-management-system'); ?></span>
</button>
</div>
</div>
</div>
</form>
<transition name="slide-fade">
<div class="stm-lms-message" v-bind:class="status" v-if="message">
{{ message }}
</div>
</transition>
</div>
<?php
if (isset($_POST['register'])) {
extract($_POST);
$servername = "localhost ";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `wp_usermeta` (its,mauze)
VALUES ('$its','$mazue')";
if ($conn->query($sql) === TRUE) {
header('Location: register.php');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>

How to retain Form data After Incomplete Form Submission

This is my code,
PHP
if(isset($_POST['submit'])){
if (empty($_POST["name"])) {
$NameErr = "Name is required";
} else {
$name = Test_User_Input($_POST["name"]);
$name = mysqli_real_escape_string($connection , $name);
}
if (empty($_POST["contact"])) {
$ContactErr = "Contact is required";
} else {
$contact = Test_User_Input($_POST["contact"]);
$contact = mysqli_real_escape_string($connection , $contact);
}
if (empty($_POST["email"])) {
$EmailErr = "Email is required";
} else {
$email = Test_User_Input($_POST["email"]);
$email = mysqli_real_escape_string($connection , $email);
}
if (empty($_POST["pan"])) {
$PanErr = "PAN is required";
} else {
$pan = Test_User_Input($_POST["pan"]);
$pan = mysqli_real_escape_string($connection , $pan);
}
if (empty($_POST["dob"])) {
$DobErr = "DOB is required";
} else {
$dob = Test_User_Input($_POST["dob"]);
$dob = mysqli_real_escape_string($connection , $dob);
}
if (empty($_POST["gender"])) {
$GenderErr = "Gender is required";
} else {
$gender = Test_User_Input($_POST["gender"]);
$gender = mysqli_real_escape_string($connection , $gender);
}
if (!empty($name) && !empty($contact) && !empty($email) && !empty($pan) &&
!empty($dob) && !empty($gender){
$query = "INSERT INTO form ( name, contact, email, pan, birthday,
gender )VALUES ('$name' , '$contact' , '$email' , '$pan' , '$dob' ,
'$gender')";
}
if ($insert_query) {
echo "Form Filled";
} else {
echo "Please Fill the form";
}
}
function Test_User_Input($Data)
{
return $Data;
}
HTML
<form action="" autocomplete="off" method="post">
<div class="col-md-6 col-sm-6 col-xs-12 marB20">
<div class="form-group-kyc">
<label>Full Name:</label><span class = "error_msg"><?php echo $NameErr; ?></span>
<input type="text" name="name" id="name" placeholder="Full Name" class="form-control-kyc" value="<?php echo isset($_POST['name']) ? $_POST['name'] :' '?> ">
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 marB20">
<div class="form-group-kyc">
<label>Contact Number:</label><span class = "error_msg"><?php echo $ContactErr; ?></span>
<input type="text" name="contact" id="contact" placeholder="Contact Number" class="form-control-kyc" value="<?php echo isset($_POST['contact']) ? $_POST['contact'] : '' ?> ">
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 marB20">
<div class="form-group-kyc">
<label>Email Id:</label><span class = "error_msg"><?php echo $EmailErr; ?></span>
<input type="email" name="email" id="email" placeholder="Email id" class="form-control-kyc" value="<?php echo isset($_POST['email']) ? $_POST['email'] : '' ?> ">
</div>
</div>
<div class="col-md-6 col-xs-12 col-sm-6 marB20">
<div class="form-group-kyc">
<label>PAN:</label><span class = "error_msg"><?php echo $PanErr; ?></span>
<input type="text" name="pan" id="pan" placeholder="PAN Card No." class="form-control-kyc" value="<?php echo isset($_POST['pan']) ? $_POST['pan'] : '' ?> ">
</div>
</div>
<div class="col-md-6 col-xs-12 col-sm-6 marB20">
<div class="form-group-kyc">
<label>DOB:</label><span class = "error_msg"><?php echo $DateErr; ?></span>
<input type="date" name="dob" id="dob" placeholder="DOB." class="form-control-kyc" value="">
</div>
</div>
<div class="col-md-6 col-xs-12 col-sm-6 marB20">
<div class="form-group-kyc">
<label>Gender:</label> <span class = "error_msg"><?php echo $GenderErr; ?></span>
<select name ="gender" id = "gender" class="form-control-kyc">
<option value="male"> Male </option>
<option value="female"\> Female </option>
</select>
</div>
</div>
<div class="col-md-12 marT30">
<div class="form-group-kyc">
<input type="submit"
id="submit" name = "submit" class="itg-button" value="Submit">
</div>
</form>
I want to Know, when the user fails to submit the form, how can I retain the form values, so user don't have to refill it.
Also if user forgets to fill one value , How to focus on that particular Field.?
ALSO
when the form is submitted and when I refresh The page, the form is again Refilled and data is sent again.
How can I prevent that?
One option is to redirect to another page after the submission, but again when the user will press back button, the form data is sent again.
Is there anything here which can be done?
For retain the filled values of the fields.
<input type="text" name="name" id="name" placeholder="Full Name" class="form-control-kyc" value="<?php echo if(isset($_POST['$name'])? $_POST['name'] : ''; ) ?>">
To avoid the auto resubmission of the data you can check whether the submit button pressed or not, if not the form data will not be added to Database and redirect it to index.php
<?php
if(isset($_POST['your-submit-button-name'])){
//within this curly brackets add your codes
}else{
header('Location: index.php');
die();
}
?>
If you want to keep the values stored you can simply echo the post value back as shown below.
<input type="text" name="name" id="name" placeholder="Full Name" class="form-control-kyc" value="<?php echo isset($_POST['name']) ? $_POST['name'] : '' ?>">

How to show selected image and its name?

I am studying and simply making an user registration form where there are several fields and the user has to upload its profile picture. I use php in order to validate the data before submitting.
After hitting the submit button it validates the data and refreshes the page due to which the filled data is gone. So we use ex. value="<?php echo $name; ?>" in the input value in order to preserve the data inserted by the user. It is possible with the simple input types such as text and others but how do we preserve the data of the image and show it in the image container and show the name of the selected image in the input type file.
<!DOCTYPE html>
<!-- form -->
<?php
$nameError = $genderError = $emailError = $mobileError = $imageError = "";
$name = $gender = $email = $mobile = $image = "";
$imagePath = $_FILES['image']['name'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameError = "Please provide Name";
} else {
$name = validateInput($_POST["name"]);
}
if (empty($_POST["gender"])) {
$genderError = "Please select Gender";
} else {
$gender = validateInput($_POST["gender"]);
}
if (empty($_POST["email"])) {
$emailError = "Please provide Email ID";
} else {
$email = validateInput($_POST["email"]);
}
if (empty($_POST["mobile"])) {
$mobileError = "Please provide Mobile Number";
} else {
$mobile = validateInput($_POST["mobile"]);
}
if (empty($_POST["image"])) {
$imageError = "Please provide Image";
} else {
$image = validateInput($_POST["image"]);
}
}
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html lang="en" dir="ltr">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/master.css">
<!-- style -->
<style media="screen">
.center {
text-align: center;
}
.required {
color: #ff0000;
}
form {
margin-bottom: 50px;
}
</style>
</head>
<body>
<div class="center container-fluid" style="margin: 50px;">
<h1 class="display-1">User Registration</h1>
</div>
<div class="container">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<!-- name -->
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Name</span>
</div>
<input type="text" class="form-control" name="name" value="<?php echo $name; ?>">
</div>
<span class="required"><?php echo $nameError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Gender</span>
</div>
<select class="form-control" name="gender">
<option <?php if (isset($gender) && $gender == "") echo "selected" ?> value="">Select your gender</option>
<option <?php if (isset($gender) && $gender == "1") echo "selected" ?> value="1">Male</option>
<option <?php if (isset($gender) && $gender == "0") echo "selected" ?> value="0">Female</option>
</select>
</div>
<span class="required"><?php echo $genderError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Email</span>
</div>
<input class="form-control" type="email" name="email" value="<?php echo $email; ?>">
</div>
<span class="required"><?php echo $emailError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Mobile</span>
</div>
<input class="form-control" minlength="10" maxlength="10" type="tel" name="mobile" value="<?php echo $mobile; ?>">
</div>
<span class="required"><?php echo $mobileError; ?></span>
</div>
<!-- image container -->
<div class="form-group" id="image_container" style="display: none;">
<img src="#" id="selected_image" width="300" height="175">
</div>
<?php echo $imagePath; ?>
<?php
if (isset($imagePath) && $imagePath != "") {
echo
"<script type='text/javascript'>
document.getElementById('image_container').style.display = 'block';
document.getElementById('selected_image').src = '" . $imagePath ."';
</script>";
}
?>
<!-- image -->
<div class="form-group">
<input class="form-control" type="file" name="image" onchange="readURL(this)">
<span class="required"><?php echo $imageError; ?></span>
</div>
<!-- submit -->
<center>
<input type="submit" class="btn btn-info">
<center>
</form>
</div>
</body>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#selected_image').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
document.getElementById("image_container").style.display = "block";
}
}
</script>
</html>
Please have a look and help and suggest me.

How do I creat a jquery form validator

I am trying to create a dynamic website using php. The site is uploaded to a free domain this is my first real world project so I want to put in as best as I can. I created a modal, in it there is a form and I want this from to validate and without refreshing the page. but I don't know why my mail() is not working please can someone tell me what I am doing wrong.
This is my fixed form inside the modal:
<div class="modal fade" id="myModal" tabindex="-1" role="form" aria-labelledby="#modalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title " id="modalLabel">Send
<?php echo
$brandName; ?> a message</h3>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="thumbnail">
<form action="contact_process.php" method="POST" role="form" autocomplete="off" class="form-container">
<small>
<i class="text-center
text-danger">all fields are required</i>
</small>
<div class="form-group has-danger">
<label class="sr-only" for="name">Name
</label>
<input type="text" name="name" placeholder="Your Name" class="form-control" id="mail-name" tabindex="1">
</div>
<div class="form-group has-danger">
<label class="sr-only" for="email">Email
</label>
<input type="email" name="email" placeholder="Your E-mail" class="form-control" id="mail-email" tabindex="2">
</div>
<div class="form-group has-danger">
<label for="tel" class="sr-only">Tell
no.
</label>
<input type="text" name="phone" placeholder="Your Phone Number" class="form-control" id="mail-
phone" tabindex="3">
</div>
<div class="form-group has-danger">
<label for="message" class="sr-only">
</label>
<textarea class="form-control
form-textarea" placeholder="Message" rows="5" spellcheck="true" name="message" id="mail-message" tabindex="4"></textarea>
</div>
<input type="button" class="btn
btn-danger" data-dismiss="modal" aria-label="Close" value="Cancel" tabindex="5">
<input id="mail-submit" type="submit" class="btn btn-primary" value="Send Message" name="submit" data- submit="...Sending" tabindex="6">
<p class="form-msg"></p>
</form>
</div>
<!--END thumbnail-->
</div>
<!--END col-->
</div>
<!--END row-->
</div>
<!--modal-body-->
</div>
<!--modal-content-->
</div>
<!--modal-dialog-->
</div>
<!---modal-->
This is the php form validation in my includes folder:
<pre>
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$errorEmpty = false;
$errorEmail = false;
$errorPhone = false;
if (empty($name) || empty($email) || empty($phone) || empty($message)) {
echo "<span class='err'>Fill in all fields!</span>";
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='err'>Invalid email please make sure you enter a
valid email address!</span>";
$errorEmail = true;
}
elseif (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?
\d{3}[\s-]?\d{4}$/i",$phone)) {
echo "<span class='err'>Please enter only a valid phone number!
</span>";
$errorPhone = true;
}
else{
// add resipeants
$to = "danjumashiwaju#gmail.com";
// create subject
$subject = "$name sent you a message from www.djshumzy.com";
// construct a message
$msg = "Name: $name\r\n";
$msg .= "Email: $email\r\n";
$msg .= "Tell: $phone\r\n";
$msg .= "Message: \r\n$message";
$msg = wordwrap($meg, 70);
//set mail header
$headers = "MINE-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=1so-8859-1\r\n";
$headers .= "From: $name <$email>\r\n";
$headers .= "X-priority: 1\r\n";
$headers .= "X-MSMail-priority: High1\r\n\r\n";
mail( $to, $subject, $msg, $headers);
} if (mail === 1) {
echo "<span class='suc'>Thank You!...Your Message has been Sent !
</span>";
}
}
?>
<script>
$("#mail-name, #mail-email, #mail-phone,
#mail-message").removeClass("input-error");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorEmail = "<?php echo $errorEmail; ?>";
var errorPhone = "<?php echo $errorPhone; ?>";
if (errorEmpty == true) {
$("#mail-name, #mail-email, #mail-phone,
#mail-message").addClass("input-error");
}
if (errorEmail == true) {
$("#mail-email").addClass("input-error");
}
if (errorPhone == true) {
$("#mail-phone").addClass("input-error");
}
if (errorEmpty == false && errorEmail == false && errorPhone == false) {
$("#mail-name, #mail-email, #mail-phone, #mail-message").val("");
}
</script>
</pre>
Here is my jquery validation(.js)
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var phone = $("#mail-phone").val();
var message = $("#mail-message").val();
var submit = $("#mail-submit").val();
$(".form-msg").load("includes/contact_process.php", {
name: name,
email: email,
phone: phone,
message: message,
submit: submit
});
});
});// END FORM VALIDATING
Please what do I have to do to make this from submit to emails and validate at the same time.
Thus the form validates but it does not send the email and just gives an error message instead.
Use https://jqueryvalidation.org/
$( "#myform" ).validate({
rules: {
field: {
required: true
},
email: {
required: true,
email: true
}
},
messages: {
field: "Please Enter Your Name",
email: "Please Enter Your Email Address"
}
});
<link href="https://jqueryvalidation.org/files/demo/site-demos.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="myform">
<label for="field">Enter Name : </label>
<input type="text" class="left" id="field" name="field">
<br/>
<label for="email">Email Address: </label>
<input type="text" id="email" name="email">
<br/>
<input type="submit" value="Validate!">
</form>
This jQuery plugin makes simple clientside form validation easy.

Categories

Resources