How to display validation errors in my website? - php

I just want this PHP code to display form validation errors in my website whenever someone uses the form incorrectly. Here is the code and I will also include the HTML of the form.
The code is only for reference, if you have a better way of doing it, then please show me.
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$number = mysqli_real_escape_string($conn, $_POST['number']);
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
// Error handlers
// Check for empty fields
if (empty($first) || empty($last) || empty($email) || empty($number) || empty($uid) || empty($pwd)) {
header("Location: ../signup.php?signup=empty");
exit();
} else {
// Check if input characters are valid
if (!preg_match("/^[a-zA-Z'-]+$/",$first) || !preg_match("/^[a-zA-Z'-]+$/",$last)) {
header("Location: ../signup.php?signup=invalid");
exit();
} else {
// Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=invalidemail");
exit();
} else {
if (preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $number)) {
header("Location: ../signup.php?signup=invalidnumber");
exit();
} else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultcheck = mysqli_num_rows($result);
if ($resultcheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
} else {
// Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
// Insert the user into the database
$sql = "INSERT INTO users (user_first, user_last, user_email, user_number, user_uid, user_pwd) VALUES ('$first', '$last', '$email', '$number', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
header("Location: ../accountcreated.php");
exit();
}
}
}
}
} else {
header("Location: ../signup.php");
exit();
}
Here is the HTML code:
<form class="memberform" action="includes/signup.inc.php" method="POST" novalidate>
<input id="spfirst" class="form_fname" type="text" name="first" placeholder="First Name">
<span class="error_form"></span>
<input id="splast" class="form_lname" type="text" name="last" placeholder="Last Name">
<span class="error_form"></span>
<input class="form_email" type="email" name="email" placeholder="E-mail">
<span class="error_form"></span>
<input id="spnumber" class="form_tel" type="tel" name="number" placeholder="Phone number">
<span class="error_form"></span>
<input id="spuser" class="form_user" type="text" name="uid" placeholder="Username">
<span class="error_form"></span>
<input class="form_password" type="password" name="pwd" placeholder="Password">
<span class="error_form"></span>
<button type="submit" name="submit">Create Account</button>
</form>
Okay there it is. I already tried so many things a nothing seems to work... Maybe it's due to my limited knowledge with PHP.

This is not the best way to do it in my opinion, but following your current code, I suggest you do this.
In your signup.php file, add this where you want the error message to appear (within the HTML if you want):
<?php
if(isset($_GET['signup'])){
switch($_GET['signup']){
case 'empty':
$msg = 'Empty fields';
break;
case 'invalid':
$msg = 'Invalid input';
break;
case 'invalidemail':
$msg = 'Invalid email';
break;
case 'invalidnumber':
$msg = 'Invalid number';
break;
case 'usertaken':
$msg = 'User taken';
break;
default:
$msg = ''; // Default message, if any
break;
}
echo '<div class="error_div">'.$msg.'</div>'; // here's where the message appears
}
?>
That will show your messages. Obviously, feel free to change the class name and style it as you wish.
Or you can simply do something like this (changing the text and stuff depending on the result you're looking for):
<?php
if(isset($_GET['signup'])){
if($_GET['signup'] == 'empty'){
echo '<span class="error_form">Empty values</span>';
}
}
?>

Since you're redirecting users to the signup page with a specific error message (Example: usertaken), you can use $_GET to handle the errors.
So in your signup page, do this
$error should = "" ;
if(isset($_GET['signup'])) {
$error = $_GET['signup'];
if(!empty($error){
//check for specific errors
if($error == "usertaken"){
$errorMsg = "The username has already been taken, try again";
}
}
}
You can use the $errorMsg in your HTML and put it where you want to display the error and design it accordingly.
NOTE: I have not done any sanitization, trying to keep this short.

Related

Change signup page echo message based on if statement from different page

I am practicing PHP and database creation and would like to change my message based on errors from the input. I can't figure out how to pass the changed messaged back and would appreciate any help given.
This is my sign up page
<main>
<h1>Signup<h1>
<h3>
<?php
echo $errorMsg;
?>
<h3>
<form action="includes/signup.inc.php" method="post">
<input type="text" name="uid" placeholder="Username">
<input type="text" name="mail" placeholder="E-mail">
<input type="password" name="pwd" placeholder="Password">
<input type="password" name="pwd_repeat" placeholder="Repeat Password">
<button type="submit" name="signup-submit">Submit</button>
<form>
</main>
This is my processing page
if(isset($_POST['signup-submit'])){
require 'dbh.inc.php';
$Name = $_POST['uid'];
$Email= $_POST['mail'];
$Password = $_POST['pwd'];
$PasswordRepeat = $_POST['pwd_repeat'];
if(empty($Name) || empty($Email) || empty($Password) || empty($PasswordRepeat)){
header("Location: ../signup.php?error=emptyfields=1"); //Check if any field is empty
exit();
}
else if(!filter_var($Email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $Name)){
header("Location: ../signup.php?error=invalidamil&uid"); //Check if username and email is valid input
exit();
}
else if(!filter_var($Email, FILTER_VALIDATE_EMAIL)){
header("Location: ../signup.php?error=invalidamil&uid=".$Name); //Check if email is valid input
exit();
}
else if($Password !== $PasswordRepeat){
header("Location: ../signup.php?error=passwordCheck&uid=".$Name."&mail=".$Email); // Check if passwords don't match
exit();
}
$sql2 = "SELECT UserName FROM dbo.MainTable WHERE UserName = ?";
$params2 = array($Name, SQLSRV_PARAM_IN);
$stmt2 = sqlsrv_query($conn, $sql2, $params2);
if($stmt2 === false)
{
die(print_r(sqlsrv_errors(), true));
exit();
}
$row_count = sqlsrv_num_rows($stmt2);
if($row_count != 0)
{
$_SESSION['errMsg'] = "Error retrieving username";
header("location: ../register.php");
exit();
}
else if($row_count > 0)
{
$_SESSION['errMsg'] = "Username is already used";
header("Location: ../signup.php?error=UserNameTaken&uid");
exit();
}
else{
$sql = "INSERT INTO dbo.MainTable(UserName,Email,UserPassword)
VALUES (?,?,?)";
$Password = PASSWORD_HASH($_POST['pwd'], PASSWORD_DEFAULT); //Password hashing
$stmt = sqlsrv_query($conn, $sql,array(#$Name,#$Email,#$Password));
if($stmt === false){
die( print_r( sqlsrv_errors(), true));
}else{
$_SESSION['errMsg'] = "Registration completed!";
header("Location: ../signup.php?signup=COMPLETE");
exit();
}
}
I am not sure where to put a change message variable here because I couldn't get it work in the if statements.
You are providing the error message as an url paramenter, so you can access it with php $_GET
<h3>
<?php
echo $_GET['error'];
?>
<h3>

Form not submitting user input to database - PHP HTML

I have a simple form set up using html and php, I want the user inputs on signup to be saved into my database table called student with the following attributes: firstName, lastName, username, email & pswrd.
After filling the html form out, I seem to be getting the error in the URL of: "http://localhost:8888/PRCO304/signup.php?error=emptyfields&uname=kakakakakak&mail=kay#kay.com"
Please could someone take a look to see what on earth I'm doing wrong please. Nothing gets inserted into the DB?
scripts/signup-script.php:
<?php
// Checking whether the user got to this page by clicking the proper signup button.
if (isset($_POST['signup-submit'])) {
// We include the connection script so we can use it later.
// We don't have to close the MySQLi connection since it is done automatically, but it is a good habit to do so anyways since this will immediately return resources to PHP and MySQL, which can improve performance.
require 'db.php';
$firstName = $_POST['first-name'];
$lastName = $_POST['last-name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
if (empty($firstName) || empty($lastName) || empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
header("Location: ../signup.php?error=emptyfields&uname=".$username."&mail=".$email);
exit();
}
// Check for an invalid username AND invalid e-mail.
else if (!preg_match("/^[a-zA-Z0-9]*$/", $username) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?error=invalidunamemail");
exit();
}
// We check for an invalid username. In this case ONLY letters and numbers.
else if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../signup.php?error=invaliduname&mail=".$email);
exit();
}
// We check for an invalid e-mail.
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?error=invalidmail&uname=".$username);
exit();
}
// We check if the repeated password is NOT the same.
else if ($password !== $passwordRepeat) {
header("Location: ../signup.php?error=passwordcheck&uname=".$username."&mail=".$email);
exit();
}
else {
// First we create the statement that searches our database table to check for any identical usernames.
$sql = "SELECT username FROM student WHERE username = ?;";
// We create a prepared statement.
$stmt = mysqli_stmt_init($conn);
// Then we prepare our SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error we send the user back to the signup page.
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
// Next we need to bind the type of parameters we expect to pass into the statement, and bind the data from the user.
// In case you need to know, "s" means "string", "i" means "integer", "b" means "blob", "d" means "double".
mysqli_stmt_bind_param($stmt, "s", $username);
// Then we execute the prepared statement and send it to the database!
mysqli_stmt_execute($stmt);
// Then we store the result from the statement.
mysqli_stmt_store_result($stmt);
// Then we get the number of result we received from our statement. This tells us whether the username already exists or not!
$resultCount = mysqli_stmt_num_rows($stmt);
// Then we close the prepared statement!
mysqli_stmt_close($stmt);
// Here we check if the username exists.
if ($resultCount > 0) {
header("Location: ../signup.php?error=usertaken&mail=".$email);
exit();
}
else {
// If we got to this point, it means the user didn't make an error! :)
// Next thing we do is to prepare the SQL statement that will insert the users info into the database. We HAVE to do this using prepared statements to make this process more secure. DON'T JUST SEND THE RAW DATA FROM THE USER DIRECTLY INTO THE DATABASE!
// Prepared statements works by us sending SQL to the database first, and then later we fill in the placeholders (this is a placeholder -> ?) by sending the users data.
$sql = "INSERT INTO student (firstName, lastName, username, email, pswrd) VALUES (?, ?, ?, ?, ?);";
// Here we initialize a new statement using the connection from the db.php file.
$stmt = mysqli_stmt_init($conn);
// Then we prepare our SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error we send the user back to the signup page.
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sssss", $firstName, $lastName, $username, $email, $hashedPwd);
// Then we execute the prepared statement and send it to the database!
// This means the user is now registered! :)
mysqli_stmt_execute($stmt);
// Lastly we send the user back to the signup page with a success message!
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
// Then we close the prepared statement and the database connection!
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
// If the user tries to access this page an inproper way, we send them back to the signup page.
header("Location: ../signup.php");
exit();
}
signup.php:
<?php
// Here we create an error messages if the user made an error trying to sign up.
if (isset($_GET["error"])) {
if ($_GET["error"] == "emptyfields") {
echo '<p class="signuperror">Fill in all fields!</p>';
}
else if ($_GET["error"] == "invalidunamedmail") {
echo '<p class="signuperror">Invalid username and email!</p>';
}
else if ($_GET["error"] == "invaliduname") {
echo '<p class="signuperror">Invalid username!</p>';
}
else if ($_GET["error"] == "invalidmail") {
echo '<p class="signuperror">Invalid email!</p>';
}
else if ($_GET["error"] == "passwordcheck") {
echo '<p class="signuperror">Your passwords do not match!</p>';
}
else if ($_GET["error"] == "usertaken") {
echo '<p class="signuperror">Username is already taken!</p>';
}
}
// Here we create a success message if the new user was created.
else if (isset($_GET["signup"])) {
if ($_GET["signup"] == "success") {
echo '<p class="signupsuccess">Signup successful!</p>';
}
}
?>
<form action="scripts/signup-script.php" method="post">
<div class="signupContainer">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<?php
if (!empty($_GET["first-name"])) {
echo '<label for="first-name"><b>First Name</b></label>
<input type="text" placeholder="First Name" name="first-name" value="'.$_GET["first-name"].'">';
} else {
echo '<label for="first-name"><b>First Name</b></label>
<input type="text" placeholder="First Name" name="first-name">';
}
if (!empty($_GET["last-name"])) {
echo '<label for="last-name"><b>Last Name</b></label>
<input type="text" placeholder="Last Name" name="last-name" value="'.$_GET["last-name"].'">';
} else {
echo '<label for="last-name"><b>Last Name</b></label>
<input type="text" placeholder="Please Enter Last Name" name="last-name">';
}
if (!empty($_GET["username"])) {
echo '<label for="username"><b>Username</b></label>
<input type="text" placeholder="Username" name="username" value="'.$_GET["username"].'">';
} else{
echo '<label for="username"><b>Username</b></label>
<input type="text" placeholder="Username" name="username">';
}
if (!empty($_GET["email"])) {
echo '<label for="email"><b>Email</b></label>
<input type="text" placeholder="Email" name="email" value="'.$_GET["email"].'">';
} else {
echo '<label for="email"><b>Email</b></label>
<input type="text" placeholder="Email" name="email">';
}
?>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Password" name="psw">
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat">
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="submit" class="signupBtn" name="signup-submit">Sign Up</button>
</div>
</div>
</form>
The issue is that your form has name="psw" and name="psw-repeat" while your script looks for $_POST['pwd']; and $_POST['pwd-repeat']; psw vs pwd
While we're at it, we could simplify the scripts a bit:
scripts/signup-script.php:
<?php
// Checking whether the user got to this page by clicking the proper signup button.
if (!isset($_POST['signup-submit'])) {
// If the user tries to access this page an inproper way, we send them back to the signup page.
header('Location: ../signup.php');
exit();
}
// We include the connection script so we can use it later.
// We don't have to close the MySQLi connection since it is done automatically,
// but it is a good habit to do so anyways since this will immediately return
// resources to PHP and MySQL, which can improve performance.
require 'db.php';
$firstName = !empty($_POST['first-name']) ? $_POST['first-name'] :'';
$lastName = !empty($_POST['last-name']) ? $_POST['last-name'] : '';
$username = !empty($_POST['username']) ? $_POST['username'] : '';
$email = !empty($_POST['email']) ? $_POST['email'] : '';
$password = !empty($_POST['pwd']) ? $_POST['pwd'] : '';
$passwordRepeat = !empty($_POST['pwd-repeat']) ? $_POST['pwd-repeat'] : '';
$location = null;
switch (true) {
case !$firstName || !$lastName || !$username || !$email || !$password || !$passwordRepeat:
$location = "Location: ../signup.php?error=emptyfields&uname=$username&mail=$email";
break;
case !preg_match('/^[a-zA-Z0-9]*$/', $username) && !filter_var($email, FILTER_VALIDATE_EMAIL):
// Check for an invalid username AND invalid e-mail.
$location = 'Location: ../signup.php?error=invalidunamemail';
break;
case !preg_match('/^[a-zA-Z0-9]*$/', $username):
// We check for an invalid username. In this case ONLY letters and numbers.
$location = "Location: ../signup.php?error=invaliduname&mail=$email";
break;
case !filter_var($email, FILTER_VALIDATE_EMAIL):
// We check for an invalid e-mail.
$location = "Location: ../signup.php?error=invalidmail&uname=$username";
break;
case $password !== $passwordRepeat:
// We check if the repeated password is NOT the same.
$location = "Location: ../signup.php?error=passwordcheck&uname=$username&mail=$email";
break;
}
// if we had errors, stop here
if ($location) {
header($location);
exit();
}
// First we create the statement that searches our database table to check for any identical usernames.
$sql = "SELECT username FROM student WHERE username = ?;";
// We create a prepared statement.
$stmt = mysqli_stmt_init($conn);
// Then we prepare our SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error we send the user back to the signup page.
header("Location: ../signup.php?error=sqlerror");
exit();
}
// Next we need to bind the type of parameters we expect to pass into the statement, and bind the data from the user.
// In case you need to know, "s" means "string", "i" means "integer", "b" means "blob", "d" means "double".
mysqli_stmt_bind_param($stmt, "s", $username);
// Then we execute the prepared statement and send it to the database!
mysqli_stmt_execute($stmt);
// Then we store the result from the statement.
mysqli_stmt_store_result($stmt);
// Then we get the number of result we received from our statement. This tells us whether the username already exists or not!
$resultCount = mysqli_stmt_num_rows($stmt);
// Then we close the prepared statement!
mysqli_stmt_close($stmt);
// Here we check if the username exists.
if ($resultCount > 0) {
header("Location: ../signup.php?error=usertaken&mail=".$email);
exit();
}
// If we got to this point, it means the user didn't make an error! :)
// Next thing we do is to prepare the SQL statement that will insert the users info into the database. We HAVE to do this using prepared statements to make this process more secure. DON'T JUST SEND THE RAW DATA FROM THE USER DIRECTLY INTO THE DATABASE!
// Prepared statements works by us sending SQL to the database first, and then later we fill in the placeholders (this is a placeholder -> ?) by sending the users data.
$sql = "INSERT INTO student (firstName, lastName, username, email, pswrd) VALUES (?, ?, ?, ?, ?);";
// Here we initialize a new statement using the connection from the db.php file.
$stmt = mysqli_stmt_init($conn);
// Then we prepare our SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error we send the user back to the signup page.
$error = mysqli_stmt_error($stmt);
header("Location: ../signup.php?error=sqlerror&description=$error");
exit();
}
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sssss", $firstName, $lastName, $username, $email, $hashedPwd);
// Then we execute the prepared statement and send it to the database!
// This means the user is now registered! :)
mysqli_stmt_execute($stmt);
// Lastly we send the user back to the signup page with a success message!
header("Location: ../signup.php?signup=success");
// Then we close the prepared statement and the database connection!
mysqli_stmt_close($stmt);
mysqli_close($conn);
exit();
signup.php:
<?php
$statusMessage = '';
if (isset($_GET['error'])) {
// Here we create an error messages if the user made an error trying to sign up.
$errorMap = [
'emptyfields' => 'Fill in all fields!',
'invalidunamedmail' => 'Invalid username and email!',
'invaliduname' => 'Invalid username!',
'invalidmail' => 'Invalid email!',
'passwordcheck' => 'Your passwords do not match!',
'usertaken' => 'Username is already taken!',
];
$message = $errorMap[$_GET['error']] ?: 'An unknown error occurred';
$statusMessage = "<p class='signuperror'>$message</p>";
}
else if (isset($_GET['signup']) && $_GET['signup'] === 'success') {
// Here we create a success message if the new user was created.
$statusMessage = '<p class="signupsuccess">Signup successful!</p>';
}
$firstName = !empty($_GET['first-name']) ? $_GET['first-name'] :'';
$lastName = !empty($_GET['last-name']) ? $_GET['last-name'] : '';
$username = !empty($_GET['username']) ? $_GET['username'] : '';
$email = !empty($_GET['email']) ? $_GET['email'] : '';
$password = !empty($_GET['pwd']) ? $_GET['pwd'] : '';
$passwordRepeat = !empty($_GET['pwd-repeat']) ? $_GET['pwd-repeat'] : '';
?>
<?= $statusMessage ?>
<form action="scripts/signup-script.php" method="post">
<div class="signupContainer">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="first-name"><b>First Name</b></label>
<input type="text" placeholder="First Name" name="first-name" value="<?= $firstName ?>">
<label for="last-name"><b>Last Name</b></label>
<input type="text" placeholder="Last Name" name="last-name" value="<?= $lastName ?>">
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Username" name="username" value="<?= $username ?>">
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Email" name="email" value="<?= $email ?>">
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Password" name="pwd">
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="pwd-repeat">
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="submit" class="signupBtn" name="signup-submit">Sign Up</button>
</div>
</div>
</form>

MySQL & PHP Sign-up Form

Hy :) Basically i am struggling with the same Problem as this Boy over here: PHP Sign-up Form Not Working - I think we were going through the same youtube tutorial :D
unfortunately i could not comment on this topic, that is why i am opening a new one. The thing is that my signup.php should be correct (at least the inputs right?) , but i am very likely to overlook things:
Thi signup.php File:
<?php
include_once 'header.php';
?>
<section class="main-container">
<div class="main-wrapper">
<h2>Sign up</h2>
<form class="signup-form" action="includes/signup.inc.php" method="POST">
<input type="text" name="first" placeholder="Firstname">
<input type="text" name="last" placeholder="Lastname">
<input type="text" name="email" placeholder="E-Mail">
<input type="text" name="uid" placeholder="Username">
<input type="password" name="pwd" placeholder="Password">
<button type="submit" name="submit">Sign up</button>
</form>
</div>
</section>
<?php
include_once 'footer.php';
?>
When I type in information, it keeps on displaying me signup.php?signup=empty.
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
//Error Handlers
//Check for empty fieldset
if (empty($first) || empty($last) || empty($email) || empty($uid) || empty($pwd)) {
header("Location: ../signup.php?signup=empty");
exit();
}
else {
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
header("Location: ../signup.php?signup=invalid");
exit();
}
else {
// Check if E-Mail is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=email");
exit();
}
else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
}
else {
// Hashing the Password (verschlüsseln)...
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
//Insert the User into the Database
$sql = "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES ('$first', '$last', '$email', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
}
else {
header("Location: ../signup.php");
exit();
}
Thank you very much in advance for any hint on this.
Best, Chris
update:
When adding following to the Code:
exit(var_dump(empty($first), empty($last), empty($email), empty($uid), empty($pwd)));
it returns
bool(true) bool(true) bool(true) bool(true) bool(true)

PHP signup system won't work (phpmyadmin, wampserver)

My php signup system won't connect to my locally hosted phpmyadmin database even though I've checked through spelling errors and everything seems like it should work. The header wont change even though it's stated in the PHP sign up script. Nothing is being transferred into my database(which has no errors with it). If someone could tell me what I'm doing wrong that would be great. (P.S. footer.php and header.php are correct and included in the form)
Sign up error handlers and sign up script:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST)$_POST['first'];
$last = mysqli_real_escape_string($conn, $_POST)$_POST['last'];
$email = mysqli_real_escape_string($conn, $_POST)$_POST['email'];
$username = mysqli_real_escape_string($conn, $_POST)$_POST['username'];
$password = mysqli_real_escape_string($conn, $_POST)$_POST['password'];
//Error handlers
//Check for empty fields
if (empty($first)) || (empty($last)) || (empty($email)) ||
(empty($username)) || (empty($password)) {
header("Location: ../signup.php?signup=empty");
exit();
} else {
//Check is input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || (!preg_match("/^[a-zA-
Z]*$/", $last)) {
header("Location: ../signup.php?signup=invalid");
exit();
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=empty");
exit();
} else {
$sql = "SELECT * FROM users WHERE user_username='username'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
} else {
//Hashing the password
$hashedPassword = password_hash($password,
PASSWORD_DEFAULT);
//Insert the user into the database
$sql = "INSERT INTO users (user_first, user_last,
user_email, user_username, user_password) VALUES ('$first', '$last',
'$email', '$username' '$hashedPassword');";
mysqli_query($conn, $sql);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
} else {
header("Location: ../signup.php");
exit();
}
Database connection:
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbServername = "loginsystem";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword,
$dbServername);
Sign up form(html in a php file):
<?php include_once 'header.php';?>
<section class="main-container">
<div class="wrapper">
<h2>Sign Up</h2>
<form class="Sign" action="includes/signup.inc.php" method="POST">
<input type="text" name="first" placeholder="First Name"><br>
<input type="text" name="last" placeholder="Last Name"><br>
<input type="email" name="email" placeholder="E-mail"><br>
<input type="text" name="username" placeholder="Username"><br>
<input type="password" name="password" placeholder="Password"><br>
<button type="submit" name="">Sign Up!</button><br>
</form>
</div>
</section>
<?php include_once 'footer.php';?>
Please help if you can. It would be much appreciated. Thanks!
Give the name 'submit' to submit button of your HTML Signup Page:
<button type="submit" name="submit">Sign Up!</button>
Change PHP Signup Page POST:
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
Change empty values checking of stmt to:
if ( (empty($first)) || (empty($last)) or (empty($email)) || (empty($username)) || (empty($password)) )
Change input characters validity checking if stmt to:
if ( (!preg_match("/^[a-zA-Z]*$/", $first)) || ((!preg_match("/^[a-zA-Z]*$/", $last)) ) )

PHP login form not working with mysql

<?php
if(array_key_exists("logIn",$_POST))
{
$link = mysqli_connect("dbaddress", "dbname", "dbpassword", "dbuser");
if(!$_POST['regno'])
{
$error .= "Please enter your registration number";
}
if(!$_POST['password'])
{
$error .= "Password is required!";
}
if($error!="")
{
echo "<p>There were errors in your forms!</p>".$error;
}
else
{
$query = "SELECT * FROM `users` WHERE RegistrationNo = '".mysqli_real_escape_string($link, $_POST['regno'])."'";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
if (isset($row)) {
$hashedPassword = md5(md5($row['id']).$_POST['password']);
if ($hashedPassword == $row['password']) {
$_SESSION['id'] = $row['id'];
header("Location: after_login.php");
}
else {
$error = "That email/password combination could not be found.";
}
}
else {
$error = "That email/password combination could not be found.";
}
}}
?>
<form method="post">
<center><input type="text" placeholder="Enter Username" name="regno" id="log_username" class="sidelog"/>
<input type="password" placeholder="Enter Password" name="password" id="real_pass" class="sidelog"/>
</br><button id="button_log" type="submit" name="logIn" > GO </button> </center>
</form>
The page reloads whenever I fill the form and submit it. The header isn't working. I can't seem to figure out why.If i leave the form empty, the error string is showing up properly. I used md5 encryption for the password. I concatenated the md5 of id in the database with the password and md5 encrypted the resulting string.
Try this will may help you,
if ($hashedPassword == $row['password']) {
$_SESSION['id'] = $row['id'];
header("Location: after_login.php");
die();
}

Categories