PHP PDO Registration not working - php

I am having issues with the code below for site Sign-Up Page
I am trying to implement a login and registration system for students and staff on my university course. I have two tables in the DB, one for authorised users and then the other for registered users.
Before somebody can register, I have to enter either their student ID or email into the authorised table, otherwise it should tell the user that they are not authorised to register.
My problem is that when I register, I just get told that I am not authorised. The ID and email is in the authorised DB, so there is an issue with my code, and I cannot work it out.
Thanks in advanced.
I have this function for registering
public function register($firstname, $surname, $student_id, $email, $password) {
try {
$new_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("INSERT INTO members(firstname, surname, student_id, email, password) VALUES(:fname, :sname, :sid, :smail, :spass)");
$stmt->bindparam(":fname", $firstname);
$stmt->bindparam(":sname", $surname);
$stmt->bindparam(":sid", $student_id);
$stmt->bindparam(":smail", $email);
$stmt->bindparam(":spass", $password);
$stmt->execute();
return $stmt;
} catch(PDOException $exception) {
echo $exception->getMessage();
}
}
And my registration page is as below.
<?php
require_once 'dbconfig.php';
if ($user->is_loggedin()!="") {
$user->redirect('home.php');
}
if (isset($_POST['btn-register'])) {
$fname = trim($_POST['fname']);
$sname = trim($_POST['sname']);
$student_id = trim($_POST['sid']);
$email = trim($_POST['smail']);
$password = trim($_POST['spass']);
$email_requirement = '#chester.ac.uk';
$email_verification = strpos($email, $email_requirement);
if ($fname == ""){
$error[] = "Please enter your firstname.";
} else if ($sname == "") {
$error[] = "Please enter your surname.";
} else if ($student_id == "") {
$error[] = "Please enter your Student ID.";
} else if ($email == "") {
$error[] = "Please enter your student email address.";
} else if ((!$email_verification) && (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
$error[] = "Please enter a valid Chester Univeristy email address.";
} else if ($password == "") {
$error[] = "Please enter a password";
} else if (strlen($email) < 6 ) {
$error[] = "Passwords need to be at least 6 characters.";
} else {
try {
$check_exist = $DB_con->prepare("SELECT student_id, email FROM members WHERE student_id=:sid OR email=:smail");
$check_exist->execute(array(':sid'=>$student_id, ':smail'=>$email));
$row=$check_exist->fetch(PDO::FETCH_ASSOC);
if ($row['student_id'] == $student_id) {
$error[] = "That student ID has already been registered.";
} else if ($row['email'] == $email) {
$error[] = "That email address has already been registered.";
} else {
try {
$check_auth = $DB_con->prepare("SELECT student_id, email FROM authorised WHERE student_id=:sid OR email=:smail");
$check_auth->execute(array(':sid'=>$student_id, ':smail'=>$email));
$row2=$check_auth->fetch(PDO::FETCH_ASSOC);
if (($row2['student_id'] != $student_id) || ($row['email'] != $email)) {
$error[] = "You are not authorised to register. Please contact Richard - admin#cybersecurity.bloxamrose.co.uk.";
} else {
if ($user->register($fname, $sname, $student_id, $email, $password)) {
$user->redirect('sign-up.php?joined');
}
}
} catch (PDOException $exception) {
echo $exception->getMessage();
}
}
} catch (PDOException $exception) {
echo $exception->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>University of Chester (UNOFFICIAL) - Cybersecurity Notes</title>
<meta name="description" content="Student made resource for Cybersecurity students at the University of Chester. UNOFFICIAL." />
<meta name="author" content="Richard J Bloxam-Rose" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<div class="form-container">
<form method="post">
<h2>Register</h2>
<hr />
<?php
if (isset($error)) {
foreach ($error as $error) {
?>
<div class="alert alert-danger">
<i class="glyphicon glyphicon-warning-sign"></i> <?php echo $error; ?>
</div>
<?php
}
} else if (isset($_GET['joined'])) {
?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"> Registration complete Login here.
</div>
<?php
}
?>
<div class="form-group">
<input type="text" class="form-control" name="fname" placeholder="First Name" value="<?php if (isset($error)) {echo $fname;}?>" />
</div>
<div class="form-group">
<input type="text" class="form-control" name="sname" placeholder="Surname" value="<?php if (isset($error)) {echo $sname;}?>" />
</div>
<div class="form-group">
<input type="text" class="form-control" name="sid" placeholder="Student ID" value="<?php if (isset($error)) {echo $student_id;}?>" />
</div>
<div class="form-group">
<input type="text" class="form-control" name="smail" placeholder="Student Email" value="<?php if (isset($error)) {echo $email;}?>" />
</div>
<div class="form-group">
<input type="password" class="form-control" name="spass" placeholder="Password" />
</div>
<div class="clearfix"></div>
<hr />
<div class="form-control">
<button type="submit" class="btn btn-block btn-primary" name="btn-register">
<i class="glyphicon glyphicon-open-file"></i> Register
</button>
</div>
<br />
<label>Already registered? Login</label>
</form>
</div>
</div>
</body>
</html>

Related

PHP, Bootstrap - user/password validation

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>

php signup form doesn't carry out the password length check correctly

I am trying to carry out some validation checks on a user signup form using HTML and PHP. I have tried to add in one which checks the character length of the username that's been inputted. When I run the script I do hit the correct URL error: http://localhost:8888/PRCO304/signup.php?error=invalidlengthuname=ttttttt however I do not get the html message that should be returned to the signup.php page to the user. `Which should be: "Username must be at least 8 characters long!"
scripts/signup-script.php:
<?php
// Checking whether the user got to this page by clicking the proper signup button.
if (isset($_POST['signup-submit'])) {
require 'db.php';
$firstName = $_POST['first-name'];
$lastName = $_POST['last-name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
// We check for any empty inputs.
if (empty($firstName) || empty($lastName) || empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
header("Location: ../signup.php?error=emptyfields&uname=".$username."&mail=".$email);
exit();
}
// We 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 minimum amount of characters in username.
else if (strlen($username <= 7)) {
header("Location: ../signup.php?error=invalidlengthuname=".$username);
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 {
$sql = "SELECT username FROM student WHERE username = ?;";
$stmt = mysqli_stmt_init($conn);
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 {
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 {
$sql = "INSERT INTO student (firstName, lastName, username, email, pwd) 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 {
// If there is no error then we continue the script!
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sssss", $firstName, $lastName, $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
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
// The index homepage includes the header
require 'header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Homepage</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta charset="utf-8">
<!-- CSS STYLING -->
<link href="./style.css" type="text/css" rel="stylesheet">
</head>
<body>
<!-- The start of my Foldy Grids -->
<section id="content">
<div class="container">
<section id="grid" class="clearfix">
<div class="cf show-grid">
<div class="row">
<div class="grid-1">grid-1</div>
<div class="grid-4">
<?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>';
}
else if ($_GET["error"] == "invalidlengthuname") {
echo '<p class="signuperror">Username must be at least 8 characters long!</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="pwd"><b>Password</b></label>
<input type="password" placeholder="Password" name="pwd">
<label for="pwd-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>
</div>
<div class="grid-1">grid-1</div>
</div>
</div>
</section>
</div>
</section>
<!-- The end of my Foldy Grids above -->
</body>
</html>
<?php
require 'footer.php';
?>
Corrected if (strlen($username < 7)) { you might need to put ! (not) in front of strlen.
To me your codes should look like this.
UPDATE had to specify second parameter in url &uname= and correct some double checks in your codes and tested its working fine:
$error '';
if (isset($_POST['signup-submit'])) {
require 'db.php';
$firstName = $_POST['first-name'];
$lastName = $_POST['last-name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
// We check for any empty inputs.
if (empty($firstName) || empty($lastName) || empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
$error = 'error';
header("Location: ../signup.php?error=emptyfields&uname=".$username."&mail=".$email);
exit();
}
// We check for an invalid username. In this case ONLY letters and numbers.
if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
$error = 'error';
header("Location: ../signup.php?error=invaliduname&uname=".$username);
exit();
}
// We check for minimum amount of characters in username.
if(strlen($username) < 8){
$error = 'error';
header("Location: ../signup.php?error=lenuname&uname=".$username);
exit();
}
// We check for an invalid e-mail.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = 'error';
header("Location: ../signup.php?error=invalidmail&mail=".$email);
exit();
}
// We check if the repeated password is NOT the same.
if ($password !== $passwordRepeat) {
$error = 'error';
header("Location: ../signup.php?error=passwordcheck&password=".$passwordRepeat);
exit();
}
if(empty($error)){
$sql = "INSERT INTO student (firstName, lastName, username, email, pwd) 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 {
// If there is no error then we continue the script!
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sssss", $firstName, $lastName, $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
Your 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>';
}
if ($_GET["error"] == "invalidunamedmail") {
echo '<p class="signuperror">Invalid username and email!</p>';
}
if ($_GET["error"] == "invaliduname") {
echo '<p class="signuperror">Invalid username!</p>';
}
if ($_GET["error"] == "invalidmail") {
echo '<p class="signuperror">Invalid email!</p>';
}
if ($_GET["error"] == "passwordcheck") {
echo '<p class="signuperror">Your passwords do not match!</p>';
}
if ($_GET["error"] == "usertaken") {
echo '<p class="signuperror">Username is already taken!</p>';
}
if ($_GET["error"] == "lenuname") {
echo '<p class="signuperror">Username must be at least 8 characters long!</p>';
}
}
// Here we create a success message if the new user was created.
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="pwd"><b>Password</b></label>
<input type="password" placeholder="Password" name="pwd">
<label for="pwd-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>
See screenshot
Very simple in my point of view:
In the URL you are expecting the error parameter to return invalidlengthuname
Meaning $_GET['error'] = 'invalidlengthuname', though as I see in your example and in your redirection, the $_GET['error'] is equal to invalidlengthuname=ttttttt.
You should remove the second = along with the "ttttttt" or create a second URL parameter so you can track which username the user has posted: ?error=invalidlengthuname&input=ttttttt. Note the & sign.

How to Log Users in Automatically After Registering

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()

Localhost cannot handle request PDO register user [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
i was trying to make from scratch a PDO, OOP user/register system in PHP and i got stucked in the point where I don't understand why I it's trowing me the handle request error.
This is my index.php file with login and register:
<?php
require_once('inc/config.php');
if($user->is_loggedIn()!="") {
$user->redirect('account.php');
}
// login
if(isset($_POST['login-submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username, $password)) {
$user->redirect('account.php');
}
else {
$error[] = "Username or Password are not correct!";
}
}
//register
if(isset($_POST['register-submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if($username == "") {
$error[] = "You need to specify a username!";
}
else if($password == "") {
$error[] = "Please add a password!";
}
else if(strlen($password) < 6) {
$error[] = "Password must have at least 6 characters";
}
else {
try {
$stmt = $db_connection->prepare("SELECT username FROM users WHERE username=:user_name");
$stmt->bindParam(':user_name', $username);
$stmt->execute();
// execute(array(':user_name'=>$username));
$row->$stmt->fetch(PDO::FETCH_ASSOC);
if($row['username'] == $username) {
$error[] = "Sorry, this username is already taken!";
}
else {
if($user->register($username, $password)) {
$user->redirect('index.php?success');
}
}
}
catch(Exception $e) {
echo $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login/Register</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-login">
<div class="panel-heading">
<div class="row">
<div class="col-xs-6">
Login
</div>
<div class="col-xs-6">
Register
</div>
</div>
<hr>
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<?php
if(isset($error)) {
foreach($error as $error) {
?>
<div class="alert alert-danger">
<i class="glyphicon glyphicon-warning-sign"></i> <?php echo $error; ?>
</div>
<?php
// end for each
}
// end of if statement
} else if(isset($_GET['success'])) { ?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"></i> Successfully registered! You can now log in!
</div>
<?php } ?>
<form id="login-form" action="#" method="post" role="form" style="display: block;">
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group text-center">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-login" value="Log In">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<div class="text-center">
</div>
</div>
</div>
</div>
</form>
<form id="register-form" action="#" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src="js/tabs.js"></script>
</body>
</html>
This is my config.php:
<?php
session_start();
//set timezone
date_default_timezone_set('Europe/Copenhagen');
//database credentials
define('DBHOST','localhost');
define('DBUSER','admin');
define('DBPASS','Ddy6MUXhtUz3mNpE');
define('DBNAME','notes_app');
//application address
define("BASE_URL","/");
define("ROOT_PATH",$_SERVER['DOCUMENT_ROOT'] . "/");
try {
$db_connection = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e) {
echo "Connection failed " . $e->getMessage();
die();
}
include_once('models/user.php');
$user = new User($db_connection);
And this is my user model:
<?php
class User {
private $db;
function __construct($db_connection) {
$this->db = $db_connection;
}
public function register($username, $password) {
try {
$crypted_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("INSERT INTO users(username, password) VALUES(:user_name, :user_pass)");
$stmt->execute(array(":user_name"=>$username, ":user_pass"=>$crypted_password));
return $stmt;
}
catch(Exception $e) {
echo $e->getMessage();
}
}
public function login($username, $password) {
try {
$stmt = $this->db->prepare("SELECT * FROM users WHERE username=:user_name");
$stmt->bindParam(':user_name', $username);
$stmt->execute();
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0) {
if(password_verify($username, $userRow['password'])) {
$_SESSION['user_session'] = $userRow['id'];
return true;
}
else {
return false;
}
}
}
catch(Exception $e) {
echo $e->getMessage();
}
}
public function is_loggedIn() {
if(isset($_SESSION['user_session'])) {
return true;
}
}
public function redirect($url) {
header("Location: $url");
}
public function logout() {
session_destroy();
unset($_SESSION['user_session']);
return true;
}
}
I was trying for several hours to find the problem but unfortunately I couldn't find it, I cannot neither print the var_dump because my browser is receiving the internal error 500.
The problem is because of the following lines:
In your login() method of User class,
if(password_verify($username, $userRow['password'])) { ...
And on index.php page, during the processing of registration form,
$row->$stmt->fetch(PDO::FETCH_ASSOC);
So your login() method should be like this:
public function login($username, $password) {
try {
$stmt = $this->db->prepare("SELECT * FROM users WHERE username=:user_name");
$stmt->bindParam(':user_name', $username);
$stmt->execute();
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0) {
if(password_verify($password, $userRow['password'])) {
$_SESSION['user_session'] = $userRow['id'];
return true;
}else{
return false;
}
}
}
catch(Exception $e) {
echo $e->getMessage();
}
}
And change this line
$row->$stmt->fetch(PDO::FETCH_ASSOC);
to
$row = $stmt->fetch(PDO::FETCH_ASSOC);

How to validate captcha in registration form?

I'm trying to create a registration form with a captcha, using this tutorial, but I don't know how to validate the captcha, can you help me?
<?php
include ('php/mysql_prisijungimas.php');
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message
if (empty($_POST['name'])) {//if no name has been supplied
$error[] = 'Please Enter a name ';//add to array "error"
} else {
$name = $_POST['name'];//else assign it a variable
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) {
//regular expression for email validation
$Email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['Password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['Password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM members WHERE Email ='$Email'";
$result_verify_email = mysqli_query($dbc, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$query_insert_user = "INSERT INTO `members` ( `Username`, `Email`, `Password`, `Activation`) VALUES ( '$name', '$Email', '$Password', '$activation')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (md5($_POST['norobot']) == $_SESSION['randomnr2']) {
// here you place code to be executed if the captcha test passes
echo "Hey great , it appears you are not a robot";
} else {
// here you place code to be executed if the captcha test fails
echo "you're a very naughty robot!";
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " To activate your account, please click on this link:\n\n";
$message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation";
mail($Email, 'Registration Confirmation', $message, 'From: test#gmail.com');
// Flush the buffered output.
// Finish the page:
echo '<div class="success">Thank you for
registering! A confirmation email
has been sent to '.$Email.' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system
error. We apologize for any
inconvenience.</div>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email
address has already been registered.
</div>';
}
} else {//If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc);//Close the DB Connection
} // End of the main Submit conditional.
?>
<head>
<meta charset="UTF-8">
<!-- Remove this line if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<meta name="description" content="test.">
<meta name="author" content="test">
<title>test</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/stilius.css">
</head>
<body>
<div class="container">
<hr>
<div class="home-page main">
<section class="grid-wrap" >
<header class="grid col-full">
<div class="right">
<form align="center" action="registracija.php" method="post" class="registration_form">
<fieldset>
<legend>Registracijos forma </legend>
<div class="elements">
<label for="name">Slapyvardis :</label>
<input type="text" id="name" name="name" size="25" />
</div>
<div class="elements">
<label for="e-mail">El. paštas :</label>
<input type="text" id="e-mail" name="e-mail" size="25" />
</div>
<div class="elements">
<label for="Password">slaptažodis:</label>
<input type="password" id="Password" name="Password" size="25" />
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>"
id="captchaimg" >
<label for="message">Enter the code above here :</label>
<input id="6_letters_code" name="6_letters_code" type="text">
</div>
<div class="submit">
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Registruotis!" />
</div>
</fieldset>
</form>
</div>
</body>
</html>
Captcha is just any string created using image library.Process as below:
1- create random or dictionary word string
2- store it anywhere [session in your case before displaying your registration form
3- compare session value to user submit value
Your code :
if (md5($_POST['norobot']) == $_SESSION['randomnr2'])
{
echo 'You passed captcha test';
}
$_SESSION['randomnr2'] is random string created and stored in session.before storing it is md5 encrypted.

Categories