I'm learning PHP and Bootstrap and I'm running into an issue when trying to validate my input fields.
Before I added Bootstrap I was able to validate the form but now it doesn't work.. does PHP and Bootstrap not work together for some reason in this fashion?
Particularly my page doesn't seem to be validating on the POST.
Does Bootstrap have the capability to validate user input directly???
I'm a bit confused and if I'm mixing technology's that shouldn't .. any help would be appreciated.
Thanks,
<?php require_once('../Connections/login.php'); ?>
<?php
session_start();
//initialize the session and verify user is logged in and allowed to view site
if (!isset($_SESSION['USER_ID'])) {
header("Location: login.php");
exit();
}else{
$qryUSER_ID=$_SESSION['USER_ID'];
}
//print_r($_POST);
//print_r($_SESSION);
//print_r($_GET);
?>
<?php
// define variables and set to empty values
$usernameErr = $passwordErr = $password_confirmErr = $password_matchErr = "";
$username = $password = $password_confirm = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameErr = "User name is required";
} else {
$username = test_input($_POST["username"]);
// check if username only contains letters and whitespace
if (!preg_match("/^[a-z0-9_.A-Z-' ]*$/",$username)) {
$usernameErr = "Only letters, numbers and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["password_confirm"])) {
$password_confirmErr = "Password confirm is required";
} else {
$password_confirm = test_input($_POST["password_confirm"]);
}
if ($_POST['password'] !== $_POST['password_confirm']) {
$password_matchErr = "Passwords must match";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" src="/css/bootstrap.min.css" >
<link href="/css/bootstrap.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon" />
<title>Skins Game-Add User</title>
</head>
<body>
<form method="post" action="dtlprocess.php">
<div class="form-group">
<label class="control-label colspan="3" class="font-weight-bold"><h2>Add New User</h2></label>
</div>
<div class="form-group">
<label class="control-label col-sm-2">User Name:</label><span class="error"><?php echo $usernameErr;?></span>
<div class="col-sm-10">
<input type="text" class="form-control" name="username" value="<?php echo htmlspecialchars($username);?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Password:</label><span class="error"><?php echo $passwordErr;?></span>
<div class="col-sm-10">
<input type="password" class="form-control" name="password" value="<?php echo htmlspecialchars($password);?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Password Confirm:</label><span class="error"><?php echo $password_matchErr;?></span>
<div class="col-sm-10">
<input type="password" class="form-control" name="password_confirm" value="<?php echo htmlspecialchars($password_confirm);?>">
</div>
</div>
<div class="form-group">
<input type="submit" name="addUser" value="Submit" class="btn btn-secondary"> <button type="submit" name="frmback" class="btn btn-secondary">Cancel</button></td>
</div>
</form>
</body>
</html>
In case anyone runs across a similar problem in the future... here is the modified code using a paramater mysqli.
It seems like Bootstrap should have some built in functionality for validating Usernames and validating passwords, therefore eliminating some of the php code.
Thanks,
<?php require_once('../Connections/login.php'); ?>
<?php
session_start();
//initialize the session and verify user is logged in and allowed to view site
if (!isset($_SESSION['USER_ID'])) {
header("Location: login.php");
exit();
}else{
$qryUSER_ID=$_SESSION['USER_ID'];
}
//print_r($_POST);
//print_r($_SESSION);
//print_r($_GET);
?>
<?php
// define variables and set to empty values
$usernameErr = $passwordErr = $password_confirmErr = $password_matchErr = "";
$username = $password = $password_confirm = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameErr = "User name is required";
} else {
$username = test_input($_POST["username"]);
// check if username only contains letters and whitespace
if (!preg_match("/^[a-z0-9_.A-Z-' ]*$/",$username)) {
$usernameErr = "Only letters, numbers and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["password_confirm"])) {
$password_confirmErr = "Password confirm is required";
} else {
$password_confirm = test_input($_POST["password_confirm"]);
}
if ($_POST['password'] !== $_POST['password_confirm']) {
$password_matchErr = "Passwords must match";
} else {
//Past the validation checks, add new user
//this also tests if the user exists before trying to add user since it will throw an error
if (isset($_POST['addUser'])){
//query if user exists already
$checkuser = $mysqli->prepare("SELECT * FROM users WHERE user_name = ?");
$checkuser->bind_param("s", $_POST['username']);
$checkuser->execute();
//row count will be > 0 if user exists
$checkrows= $checkuser->get_result();
$checkuser->close();
if($checkrows->num_rows > 0) {
echo "User already exists";
exit();
}else{
//Add new user since they do not exist
$activeuser = 'A';
$addnewuser = $mysqli->prepare("INSERT INTO users (user_name, password, active) VALUES (?,?,?)");
$addnewuser->bind_param("sss", $_POST['username'], $_POST['password'], $activeuser);
$addnewuser->execute();
$addnewuser->close();
header("Location: summary.php");
exit();
}
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" src="/css/bootstrap.min.css" >
<link href="/css/bootstrap.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon" />
<style>
.error {color: #FF0000;}
.font10{font-size: 10px;}
</style>
<title>Skins Game-Add User</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div class="form-group">
<label class="control-label colspan="3" class="font-weight-bold"><h2>Add New User</h2></label>
</div>
<div class="form-group">
<label class="control-label col-sm-2">User Name:</label><label class="error font10"><?php echo $usernameErr;?></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="username" value="<?php echo $username;?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Password:</label><span class="error font10"><?php echo $passwordErr;?></span>
<div class="col-sm-10">
<input type="password" class="form-control" name="password" value="<?php echo $password;?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Password Confirm:</label><span class="error font10"><?php echo $password_matchErr;?></span>
<div class="col-sm-10">
<input type="password" class="form-control" name="password_confirm" value="<?php echo $password_confirm;?>">
</div>
</div>
<div class="form-group">
<input type="submit" name="addUser" value="Submit" class="btn btn-secondary"> <button type="submit" name="frmback" class="btn btn-secondary">Cancel</button></td>
</div>
</form>
</body>
</html>```
Use an array of errors instead of blank variables.
You can use validation like this just create a file for this:
validation.php:
$name = test_input($_POST['name']);
$login = test_input($_POST['login']);
$email = test_input($_POST['email']);
$password = test_input($_POST['password']);
$password_confirm = test_input($_POST['password_confirm']);
$succ = [];//old value of inputes will be stored here
if(empty($name)){
$errors['name'] = 'Name required';
}else{
$succ['name'] = $name;
}
if(empty($login)){
$errors['login'] = 'Login required';
}else{
$succ['login'] = $login;
}
if(empty($email)){
$errors['email'] = 'Email required';
}else{
$succ['email'] = $email;
}
if(empty($password)){
$errors['password'] = 'password required';
}
if($password_confirm != $password){
$errors['password_confirm'] = 'Passwords are not equal';
}
if(isset($errors)){
$_SESSION['errors'] = $errors;
$_SESSION['succ'] = $succ;
header("Location: index.php");
die;
}else{
header("Location: index.php")
}
and add into form attribute action="validation.php" and add to the top of your file:
index.php
if(isset($_SESSION['errors'])){
$errors = $_SESSION['errors'];//execute errors from the session
$succ = $_SESSION['succ'];
unset($_SESSION['succ']);
unset($_SESSION['errors']);//delete all errrors from the session
}
And then you can use $errors on your page as array of errors.
After that you can add an error container for each input like that:
.
.
...<input type="text" name="name" ....
<span class="error">
<?php
if(isset($errors['name'])){
echo $errors['name'];
}
?>
</span>
Related
I've wrote this code for a comment section for my website. But that was suppose to show error message beside the '*' sign when anyone types in incorrect email or empty comment. It was doing good, but after I've added the CSS styles it is not working.
I'm reading the input and passing that to PHP. After PHP checks that, I save that to a comment folder. Or else if the format is wrong, I give an error message. But now the error message is not showing for some reason.
Link of the code running in a host https://cryptocrack.000webhostapp.com/comment/test/index.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width , initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="wrapper">
<div class="title">
<h2>Leave a comment</h2>
</div>
<div class="contact-form">
<div class="input-fields">
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" class="input" placeholder="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="text" name="email" class="input" placeholder="Email Address" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
</div>
<div class="msg">
<textarea name="comment" placeholder="Comment"><?php echo $comment;?></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br><br>
<input type="submit" name="submit" class="btn" value="Submit">
</div>
</form>
</div>
</div>
<div class="cm">
<div class="tl">
<h1>Comments</h1>
</div>
<br><br>
<?php
// define variables and set to empty values
date_default_timezone_set("Asia/Dhaka");
$nameErr = $emailErr = $commentErr = "";
$name = $email = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Comment is required";
} else {
$comment = test_input($_POST["comment"]);
}
if($nameErr==""&&$emailErr==""&&$commentErr==""){
$cd=date("d.m.Y l h:i:s a");
$d=(string)mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y"));
$cf = fopen(getcwd()."/comments/".$d.".txt", "w");
fwrite($cf, $name."\n");
fwrite($cf, $cd."\n");
fwrite($cf, $email."\n");
fwrite($cf, $comment);
fclose($cf);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$dir=getcwd()."/comments/";
$cm = scandir($dir,1);
$len = count($cm)-2;
for($i=0;$i<$len;$i++){
$f=fopen($dir.$cm[$i],"r");
echo "<div class=\"name\">" .fgets($f)."</div><div class=\"date\">".fgets($f)."</div><div class=\"email\">".fgets($f)."</div><br>";
while(!feof($f)){
echo fgets($f)."<br>";
}
echo "<br><br>";
}
?>
</div>
</body>
</html>
<?php if(isset($nameErr)){ echo $nameErr; } ?>
use that instead of
<?php echo $nameErr;?>
You get error cause the variables are not defined.
I currently have my code working to some state.
When the user inputs data name, email and company they submit the form and it will echo the inputs out which is fine, but when I enter invalid data into the form and submit it will still post but displays the else statement.
Have I missed something in my Preg_match or is this just a bad way to code the validation?
<!DOCTYPE html>
<html>
<head>
<title>Visitor Sign in</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="visitor.css"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<img src="Wincanton.png" alt="wincantonLogo" class="wincantonLogo" />
<img src="Screwfix.png" alt="screwfixLogo" class="screwfixLogo" />
<div style="clear:both"></div><br>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $companyErr = "";
$fullname = $email = $company = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fullname"])) {
$nameErr = "Name is required";
} else {
$fullname = test_input($_POST["fullname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fullname)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!preg_match("/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["company"])) {
$companyErr = "Name is required";
} else {
$company = test_input($_POST["company"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$company)) {
$companyErr = "Only letters and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h1>Visitor Sign in</h1><br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="fullname" >
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Company: <input type="text" name="company">
<span class="error"><?php echo $companyErr;?></span>
<br><br>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $fullname;
echo "<br>";
echo $email;
echo "<br>";
echo $company;
echo "<br>";
?>
</body>
</html>
try if isset condition.
if(isset($_POST['submit'])){
}
I have used header("Content-Type:text/html; charset=utf-8"); & <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> on both html & php parts.
But for the webpage contents displayed , the text of the Chinese words are garbled .How to tackle the problem ?
create.php
<?php
// Include config file
require_once 'database.php';
header("Content-Type:text/html; charset=utf-8");
print_r($_POST);
// Define variables and initialize with empty values
$CName = $Address = $Amount = "";
$CName_err = $Address_err = $Amount_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_CName = trim($_POST["CName"]);
if(empty($input_CName)){
$CName_err = "Please enter a name.";
} elseif(!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z'-.\s ]+$/")))){
$CName_err = 'Please enter a valid name.';
} else{
$CName = $input_CName;
}
// Validate address
$input_Address = trim($_POST["Address"]);
if(empty($input_Address)){
$Address_err = 'Please enter an address.';
} else{
$Address = $input_Address;
}
// Validate Amount
$input_Amount = trim($_POST["Amount"]);
if(empty($input_Amount)){
$Amount_err = "Please enter the amount.";
} elseif(!ctype_digit($input_Amount)){
$Amount_err = 'Please enter a positive integer value.';
} else{
$Amount = $input_Amount;
}
// Check input errors before inserting in database
if(empty($CName_err) && empty($Address_err) && empty($Amount_err)){
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO donation (CName, Address, Amount) VALUES (?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName,$Address,$Amount));
Database::disconnect();
header("Location: index.php");
}}
?>
<!DOCTYPE html>
<!--<html lang="en">-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>捐贈表格</h2>
</div>
<p>本人願意以信用卡捐款</p><br>
<p>I would like to make donation</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($CName_err)) ? 'has-error' : ''; ?>">
<label>Name</label>
<input type="text" name="CName" class="form-control" value="<?php echo $CName; ?>">
<span class="help-block"><?php echo $CName_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Address_err)) ? 'has-error' : ''; ?>">
<label>Address</label>
<textarea name="Address" class="form-control"><?php echo $Address; ?></textarea>
<span class="help-block"><?php echo $Address_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Amount_err)) ? 'has-error' : ''; ?>">
<label>Amount</label>
<input type="text" name="Amount" class="form-control" value="<?php echo $Amount; ?>">
<span class="help-block"><?php echo $Amount_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
<p>多謝您的支持</p><br>
<p>Thank you for your support</p>
</div>
</div>
</div>
</div>
</body>
</html>
Update
garbled page :
I'm new with using PHP. I'd like to add an auto login part to my site, so users are automatically logged in after they create an account on my site. Can someone please tell me how I can automatically log users in after they register? I am not sure where I should be starting. I appreciate all the help you can give me. Thank you so much! :)
Here is my register.php script:
<?php
ob_start();
session_start();
if( isset($_SESSION['user'])!="" ){
header("Location: /");
}
include_once 'dbconnect.php';
$error = false;
if ( isset($_POST['btn-signup']) ) {
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
$company = trim($_POST['company']);
$pcompany = strip_tags($company);
$company = htmlspecialchars($company);
if (empty($name)) {
$error = true;
$nameError = "Please enter your full name.";
} else if (strlen($name) < 3) {
$error = true;
$nameError = "Name must have atleat 3 characters.";
} else if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$nameError = "Name must contain alphabets and space.";
}
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
$query = "SELECT userEmail FROM users WHERE userEmail='$email'";
$result = mysqli_query($conn,$query);
$count = mysqli_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
}
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have atleast 6 characters.";
}
$password = hash('sha256', $pass);
if( !$error ) {
$query = "INSERT INTO users(userName,userEmail,userPass,userCompany) VALUES('$name','$email','$password','$company')";
$res = mysqli_query($conn,$query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($name);
unset($email);
unset($pass);
unset($company);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
//include your login validation
if(empty($errors)){
//User->login(); or anything you use for validating logins
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<title>Register | Hexa</title>
<link rel="icon" href="https://app.myhexa.co/favicon.ico" type="image/x-icon">
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700&subset=latin,cyrillic-ext" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css">
<link href="plugins/bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="plugins/node-waves/waves.css" rel="stylesheet" />
<link href="plugins/animate-css/animate.css" rel="stylesheet" />
<link href="css/login.css" rel="stylesheet">
</head>
<body class="signup-page bg-blue-grey">
<div class="signup-box">
<div class="logo">
<center><img src="img/logo.png" height="50" width="155"></center>
</div>
<div class="card">
<div class="body">
<form id="sign_up" method="POST">
<div class="msg"><h3 class="col-blue-grey">CREATE ACCOUNT</h3></div><br>
<?php
if ( isset($errMSG) ) {
?>
<span class="fa fa-exclamation-triangle"></span> <?php echo $errMSG; ?>
</div>
</div>
<?php
}
?>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">person</i>
</span>
<div class="form-line">
<input type="text" name="name" class="form-control" placeholder="Name" maxlength="50" value="<?php echo $name ?>" /">
</div>
</div>
<span class="text-danger"><?php echo $nameError; ?></span><br>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">email</i>
</span>
<div class="form-line">
<input type="email" name="email" class="form-control" placeholder="Email Address" maxlength="40" value="<?php echo $email ?>" />
</div>
</div>
<span class="text-danger"><?php echo $emailError; ?></span><br>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">people</i>
</span>
<div class="form-line">
<input type="text" name="company" class="form-control" placeholder="Company" value="<?php echo $company ?>" />
</div>
</div><br>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">lock</i>
</span>
<div class="form-line">
<input type="password" name="password" class="form-control" placeholder="Password" maxlength="15" id="password" required>
</div>
</div>
<span class="text-danger"><?php echo $passError; ?></span><br>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">lock</i>
</span>
<div class="form-line">
<input type="password" name="pass" class="form-control" placeholder="Confirm Password" maxlength="15" id="confirm_password" required>
</div>
</div>
<div class="form-group">
<input type="checkbox" name="terms" id="terms" class="filled-in chk-col-deep-orange">
<label for="terms">I read and agree to the terms of usage.</label>
</div>
<button type="submit" class="btn btn-block btn-lg bg-deep-orange waves-effect" name="btn-signup">REGISTER</button>
<div class="m-t-25 m-b--5 align-center">
Have An Account?
</div>
</form>
</div>
</div>
</div>
<script src="plugins/jquery/jquery.min.js"></script>
<script src="plugins/bootstrap/js/bootstrap.js"></script>
<script src="plugins/node-waves/waves.js"></script>
<script src="plugins/jquery-validation/jquery.validate.js"></script>
<script src="plugins/js/admin.js"></script>
<script>var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
</script>
</body>
</html>
<?php ob_end_flush(); ?>
From the JSFiddle you linked in the comments, you set the session after a successful login as such
$_SESSION['user'] = $row['userId'];
That means that you'd need to set the $_SESSION['user'] session as the last inserted ID after a completed registration to achieve what you're asking about. You can use the mysqli_insert_id() function to get the last inserted ID. That'd be like this
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
$_SESSION['user'] = mysqli_insert_id($conn); // Sets the session and logs the user in instantly
}
Additional info
You're already using an API that supports prepared statements with bounded variable input, you should utilize parameterized queries with placeholders (prepared statements) to protect your database against SQL-injection!
Get started with mysqli::prepare() and mysqli_stmt::bind_param().
You should also use the PHP password_* functions to hash and verify passwords, instead of using sha512.
Furthermore, you have if( isset($_SESSION['user'])!="" ){ - which compares a boolean against an empty string. It should be if (isset($_SESSION['user'])) { instead.
exit; should be added after every header("Location: .."); call, to prevent the script from executing any further.
Finally, functions such as htmlspecialchars() is intended for output and not input. These have nothing to do with "escaping" or sanitizing data, but is used to ensure that HTML is valid when outputting data from a database (and in turn, prevent XSS attacks). Password shouldn't be changed at all - JUST hash them - as the hash might be different if you use other functions on it before/after hashing.
strip_tags() might be applicable on the other variables, but I don't believe it fits here (depends, you should understand what the function does, read the manual on strip_tags()).
References
PHP.net on mysqli_insert_id()
PHP.net on password_hash() / password_verify()
My form inputs records if I format the form fields according to the regex I have established and then echo's the record being inserted into the database successfully. If I make any errors, it simply erases the fields and doesn't echo the error. I'm fairly new to php and I'm doing this for a class project as part of an online course. I'm not sure where my error is. Any help will be greatly appreciated.
<!DOCTYPE HTML>
<html lang = "en">
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Tech Order Department.html</title>
<meta charset = "UTF-8" />
<style>
div {
text-align: justify;
}
.section {
margin-left: auto;
margin-right: auto;
width: 70%;
}
</style>
</head>
<body>
<h2>Tech Orders</h2>
<br>
<title>Page Title</title>
<h2>New Project</h2>
<p class="first"><span class="error">* required field.</span></p>
<form action="http://www.oldgamer60.com/Project/try.php" method="post">
<div class="fieldset">
<fieldset>
Project: <input type="text" name="Project" value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
Client: <input type="text" name="Client" value="<?php if(isset($Client)){ echo $Client; } ?>">
<span class="error">* <?php if(isset($ClientErr)){ echo $ClientErr; } ?></span>
<br><br>
LastName: <input type="text" name="LastName" value="<?php if(isset($LastName)){ echo $LastName; } ?>">
<span class="error">* <?php if(isset($LastNameErr)){ echo $LastNameErr; } ?></span>
<br><br>
DateReceived: <input type="text" name="DateReceived" value="<?php if(isset($DateReceived)){ echo $DateReceived; } ?>">
<span class="error">* <?php if(isset($DateReceivedErr)){ echo $DateReceivedErr; } ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</div>
</form>
<br>
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['submit']) && !$connection->connect_error){
// to track errors
$error = false;
// now validate input fields
if (empty($_POST['Project']) || !isset($_POST['Project'])){
$ProjectErr = "Project name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9.-]+$/",$_POST['Project'])){
// check if project only contains number, letters, comma's periods and whitespace
$ProjectErr = "Only letters, numbers, comma's, periods and white space allowed";
$error = true;
}else{
$Project = test_input($_POST['Project']);
}
if (empty($_POST['Client']) || !isset($_POST['Client'])){
$ClientErr = "Client name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9.-]+$/",$_POST['Client'])){
// check if project only contains number, letters, comma's periods and whitespace
$ClientErr = "Only letters, numbers, comma's, periods and white space allowed";
$error = true;
}else{
$Client = test_input($_POST['Client']);
}
if (empty($_POST['LastName']) || !isset($_POST['LastName'])){
$LastNameErr = "Last name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9-]+$/",$_POST['LastName'])){
// check if last name only contains letters and whitespace
$LastNameErr = "Only letters and white space allowed";
$error = true;
}else{
$LastName = test_input($_POST['LastName']);
}
if (empty($_POST['DateReceived']) || !isset($_POST['DateReceived'])){
$DateReceivedErr = "Data received field is required";
$error = true;
}elseif(!preg_match("/^\d{4}-\d{2}-\d{2}$/",$_POST['DateReceived'])){
// check if data received only contains letters and whitespace
$DateReceivedErr = "Date must be entered as YYYY/MM/DD";
$error = true;
}else{
$DateReceived = test_input($_POST['DateReceived']);
}
if(!$error){
$query = "INSERT INTO Projects (Project, Client, LastName, DateReceived) VALUES ('$Project', '$Client', '$LastName', '$DateReceived')";
if($connection->query($query)){
echo "record is successfully inserted!";
}else{
echo "error: record could not be inserted";
}
}
}
?>
<?php
$connection->close();
?>
</div>
</div>
</body>
</html>
Check this out. In your form you use vars that are not yet defined (Tey are defined down in the code but yout trying to echo them before defining them):
Project: <input type="text" name="Project" value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
isset($ProjectErr) is never set since you setting it lower in code and also
$ProjectErr do not exist in your form
Solution, put form down under the php code where you checking input fields.
Edit:
Try something like this:
<!DOCTYPE HTML>
<html lang = "en">
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Tech Order Department.html</title>
<meta charset = "UTF-8" />
<style>
div {
text-align: justify;
}
.section {
margin-left: auto;
margin-right: auto;
width: 70%;
}
</style>
</head>
<body>
<h2>Tech Orders</h2>
<br>
<title>Page Title</title>
<h2>New Project</h2>
<p class="first"><span class="error">* required field.</span></p>
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['submit']) && !$connection->connect_error){
// to track errors
$error = false;
// now validate input fields
if (empty($_POST['Project']) || !isset($_POST['Project'])){
$ProjectErr = "Project name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9.-]+$/",$_POST['Project'])){
// check if project only contains number, letters, comma's periods and whitespace
$ProjectErr = "Only letters, numbers, comma's, periods and white space allowed";
$error = true;
}else{
$Project = test_input($_POST['Project']);
}
if (empty($_POST['Client']) || !isset($_POST['Client'])){
$ClientErr = "Client name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9.-]+$/",$_POST['Client'])){
// check if project only contains number, letters, comma's periods and whitespace
$ClientErr = "Only letters, numbers, comma's, periods and white space allowed";
$error = true;
}else{
$Client = test_input($_POST['Client']);
}
if (empty($_POST['LastName']) || !isset($_POST['LastName'])){
$LastNameErr = "Last name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9-]+$/",$_POST['LastName'])){
// check if last name only contains letters and whitespace
$LastNameErr = "Only letters and white space allowed";
$error = true;
}else{
$LastName = test_input($_POST['LastName']);
}
if (empty($_POST['DateReceived']) || !isset($_POST['DateReceived'])){
$DateReceivedErr = "Data received field is required";
$error = true;
}elseif(!preg_match("/^\d{4}-\d{2}-\d{2}$/",$_POST['DateReceived'])){
// check if data received only contains letters and whitespace
$DateReceivedErr = "Date must be entered as YYYY/MM/DD";
$error = true;
}else{
$DateReceived = test_input($_POST['DateReceived']);
}
if(!$error){
$query = "INSERT INTO Projects (Project, Client, LastName, DateReceived) VALUES ('$Project', '$Client', '$LastName', '$DateReceived')";
if($connection->query($query)){
echo "record is successfully inserted!";
}else{
echo "error: record could not be inserted";
}
}
}
?>
<?php
$connection->close();
?>
<form action="http://www.oldgamer60.com/Project/try.php" method="post">
<div class="fieldset">
<fieldset>
Project: <input type="text" name="Project" value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
Client: <input type="text" name="Client" value="<?php if(isset($Client)){ echo $Client; } ?>">
<span class="error">* <?php if(isset($ClientErr)){ echo $ClientErr; } ?></span>
<br><br>
LastName: <input type="text" name="LastName" value="<?php if(isset($LastName)){ echo $LastName; } ?>">
<span class="error">* <?php if(isset($LastNameErr)){ echo $LastNameErr; } ?></span>
<br><br>
DateReceived: <input type="text" name="DateReceived" value="<?php if(isset($DateReceived)){ echo $DateReceived; } ?>">
<span class="error">* <?php if(isset($DateReceivedErr)){ echo $DateReceivedErr; } ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</div>
</form>
<br>
</div>
</div>
</body>
</html>