DB not updating after putting the prepared statment in the code - php

So I have decided to put the prepared statement in my code and when I fill the information with all the valid details, a message pops up saying registration successful but no data actually goes in the Database
Here is the function code that I have;
//check if form is submitted
if (isset($_POST['signup'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
//name can contain only alpha characters and space
if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$name_error = "Name must contain only alphabets and space";
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$error = true;
$email_error = "Please Enter Valid Email ID";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($password != $cpassword) {
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (!$error)
{
// prepare and bind
$stmt = $con->prepare("INSERT INTO users (name,email,password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $email, $password);
if($stmt->execute = true) {
$successmsg = "Successfully Registered! <a href='login.php'>Click here to Login</a>";
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
?>
The Db structure in my php my admin;
id(int 8)
name(varchar 30)
email(varchar 60)
password(varchar 40)
I would appreciate a help, and thanks in advance!

Related

php redirect to another page after validation

I am trying to figure out how to redirect after validation of a form (i.e after conditions for my form have been met)(I have the header at the end of the PHP code). I have a basic form ,and I know this should be a straightforward code of line but I can't seem to make it work! Your advice is very much appreciated!
<?php
$firstNameErr = '';
$lastNameErr = '';
$emailErr='';
$passwordErr = '';
$passwordConfErr='';
if($_SERVER["REQUEST_METHOD"] == "POST"){
$firstName = $_POST["firstName"];
if(empty($firstName)){
$firstNameErr = "First Name is required";
}
else if(!preg_match("/^[a-zA-Z]+$/", $firstName)){
$firstNameErr= "Only letters, no spaces or special characters allowed";
}
else{
$firstNameErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$lastName = $_POST["lastName"];
if(empty($lastName)){
$lastNameErr = "Last Name is required";
}
else if(!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $lastName)){
$lastNameErr = "No Special characters or numbers allowed";
}
else{
$lastNameErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = $_POST["email"];
if(empty($email)){
$emailErr = "Email is required";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
else{
$emailErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$password=$_POST["password"];
if(empty($password)){
$passwordErr = "Please Enter your password";
}
else if (strlen($password) < "8") {
$passwordErr = "Your Password Must Contain At Least 8 Digits !";
}
else if(!preg_match("#[0-9]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Number !";
}
else if(!preg_match("#[A-Z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter !";
}
else if(!preg_match("#[a-z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter !";
}
else if(!preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $password)) {
$passwordErr = "Your Password Must Contain At Least 1 Special Character !";
}
else{
$passwordErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$confirmPassword = $_POST["confirmPassword"];
$password = $_POST["password"];
if(empty($confirmPassword)){
$passwordConfErr = "Please Enter your password";
}
else if($password!=$confirmPassword){
$passwordConfErr = "Passwords do not match";
}
else{
$passwordConfErr="Valid";
}
}
else{
echo "Form not submitted with POST";
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST['Register']) and $firstNameErr == "Valid" and $lastNameErr =="Valid" and $emailErr == "Valid" and $passwordErr == "Valid" and $passwordConfErr=="Valid") {
header("Location: profile.php");
exit();
}
}
A single if ($_SERVER["REQUEST_METHOD"] == "POST"){ which wraps all $_POST logic would suffice, then depending on your app (if its mostly AJAX) you should use a response/request flow so the POST logic is at the top and it falls through to the view with the errors which can then be used in the view, or you should return JSON and do an AJAX request, else you won't be able to pick up the errors unless you put them into the session and then pick them up on redirect which is just extra steps.
Example request/response, for a single page i.e register.php, this could be broken out where you load the HTML via an include or view loader but the idea is the same.
<?php
$errors = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// first name
if (empty($_POST["firstName"])){
$errors['firstName'] = "First Name is required";
} else if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstName"])) {
$errors['firstName'] = "Only letters, no spaces or special characters allowed";
}
// last name
if (empty($_POST["lastName"])) {
$errors['lastName'] = "Last Name is required";
} else if (!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $_POST["lastName"])) {
$errors['lastName'] = "No Special characters or numbers allowed";
}
// ...others
// errors is empty, so must all be valid
if (empty($errors)) {
// do something like insert into db and set session status
header("Location: profile.php");
exit();
}
// otherwise continue to form
} ?>
<form>
...
<input name="firstName" value="<?= htmlspecialchars($_POST['firstName'] ?? '', ENT_QUOTES, 'UTF-8') ?>"/>
<?= isset($errors['firstName']) ? '<span class="form-error">'.$errors['firstName'].'</span>' : '' ?>
<input name="lastName" value="<?= htmlspecialchars($_POST['lastName'] ?? '', ENT_QUOTES, 'UTF-8') ?>"/>
<?= isset($errors['lastName']) ? '<span class="form-error">'.$errors['lastName'].'</span>' : '' ?>
</form>
Or if your going to use mostly AJAX, another way would be to return JSON, then you can access the errors to then build out the dom from the AJAX response.
<?php
//
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// set json response header
header('Content-type: application/json;charset=utf-8');
// Is POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//
$errors = [];
// first name
if (empty($_POST["firstName"])){
$errors['firstName'] = "First Name is required";
} else if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstName"])) {
$errors['firstName'] = "Only letters, no spaces or special characters allowed";
}
// last name
if (empty($_POST["lastName"])) {
$errors['lastName'] = "Last Name is required";
} else if (!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $_POST["lastName"])) {
$errors['lastName'] = "No Special characters or numbers allowed";
}
// ...others
// errors is empty, so must all be valid
if (empty($errors)) {
// do something like insert into db and set session status
echo json_encode(['status' => 200]);
exit();
}
echo json_encode(['errors' => $errors]);
exit();
} else {
header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
echo json_encode(['status' => 405]);
}
} else {
header('Location: /');
}
In both examples, use a single errors array then its easy to access and all in one place. You also don't need to set additional vars from the $_POST['...'] vars to validate them.
Your validating code should look like this:
$Name = $Surname = $username = $password = $confirm_password =
$email ="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate Name.
if (empty(trim($_POST["firstName"]))) {
$errors[] = 'name required.';
} else {
$Name = $_POST["firstName"];
}
// Validate lastName.
if (empty(trim($_POST["lastName"]))) {
$errors[] = 'surname required.';
} else {
$Surname = $_POST["lastName"];
}
// Validate username
if (!preg_match("/^[a-zA-Z]+$/", $_POST["username"])) {
$errors['username'] = "Only letters, no spaces or special characters allowed";
}
// Validate username from database to see if username already exist.
//You can check for the email is well.
if(empty(trim($_POST["username"]))){
$errors[] = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = :username";
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":username", $param_username, PDO::PARAM_STR);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() == 1){
$errors[] = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
$stmt->closeCursor();
}
}
// Validate password
if(empty(trim($_POST["password"]))){
$errors[] = "Enter password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$errors[] = "password should be min 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$errors[] = "confirm pass.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if($password != $confirm_password){
$errors[] = "pass no matches.";
}
}
// Validate Email
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$email = $_POST["email"];
} else {
$errors[] = "invalid email type.";
}
// Validate Email
if(empty(trim($_POST["email"]))){
$errors[] = 'email required.';
}else {
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
}
if(empty($errors)){
//if no errors
//Do everythin else in here
//Do insert query after you are done redirect to profile page
header("Location: profile.php");
exit();
}
}
To get eroors :
<?php if(isset($errors)) {?>
<div class="error">
<?php echo implode('<br/>', $errors); ?>
</div>
<?php } unset($_SESSION['errors']); ?>
And your html form here if its in same page :
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
//inputs etc..
</form>

localhost: data not going into database

i am trying to make a registration system but when i register the data isn't there.
i tried to search same questions but i couldn't find the issue, and the worst is that the script detect the database but wont get the data in.
The PHP script :
<?php
$bdd = new PDO('mysql:host=127.0.0.1;dbname=fireblock', 'root', '');
if(isset($_POST['submitform'])) {
$username = htmlspecialchars($_POST['username']);
$email = htmlspecialchars($_POST['email']);
$email2 = htmlspecialchars($_POST['email2']);
$pass = sha1($_POST['pass']);
$pass2 = sha1($_POST['pass2']);
if(!empty($_POST['username']) AND !empty($_POST['email']) AND !empty($_POST['email2']) AND !empty($_POST['pass']) AND !empty($_POST['pass2'])) {
$usernamelength = strlen($username);
if($usernamelength <= 255) {
if($email == $email2) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
$reqemail = $bdd->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
if($pass == $pass) {
$insertmbr = $bdd->prepare("INSERT INTO members(username, email, pass) VALUES(?, ?, ?)");
$insertmbr->execute(array($username, $email, $pass));
$error = "Your account has been created! Connect";
} else {
$error = "Your passs are not the same!";
}
} else {
$error = "Email already used!";
}
} else {
$error = "Your email is invalid!";
}
} else {
$error = "Your emails are not the same!";
}
} else {
$error = "Your username can't get upper than 255 characters!";
}
} else {
$error = "Every fields should be filled!";
}
}
?>

How do I redirect a user to the same URL if the password/email validation fails?

I have a password reset script that has email and password validation. How can I make the script redirect the user to the same URL (ie. "https://www.domain.com/resetpassword.php?token=...") if they fail to meet the validation? Currently, if the validation test fails, the user is redirected to the URL: https://www.domain.com/resetpassword.php. The token is now gone and the password reset page becomes useless.
Here is my PHP code:
<?php
ob_start();
session_start();
include 'connect.php';
// Was the form submitted?
if (isset($_POST['btn-reset']))
{
// Gather the post data
$email = trim($_POST['email']);
$email = strip_tags($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$cpass = trim($_POST['cpass']);
$cpass = strip_tags($cpass);
//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have at least 6 characters.";
} else if($pass != $cpass) {
$error = true;
$passError = "Passwords do not match.";
}
// if there's no error, continue to process
if( !$error ) {
$token = $_POST ['token'];
// Retrieve token from database
$stmt = $conn->prepare('SELECT token FROM token WHERE userEmail=? and NOW() < expire_date');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$resetKey = $row['token'];
}
// Does the new reset key match the old one?
if ($resetKey == $token && isset($token))
{
if ($pass == $cpass)
{
//hash and secure the password
$password = password_hash($pass, PASSWORD_DEFAULT);
// Update the user's password
$stmt = $conn->prepare('UPDATE user SET userPass = ? WHERE userEmail = ?');
$stmt->bind_param('ss', $password, $email);
$stmt->execute();
$conn = null;
$sucMSG = "Your password has been successfully reset.";
unset($email);
unset($pass);
unset($cpass);
unset($token);
unset($resetKey);
}
else
$matchError = "Your password's do not match.";
}
else
$keyError = "Your password reset key is invalid.";
}
}
?>
And then I have the errors appear in my form using PHP if the values of the errors are set.

PHP getting error message when i try to register with php page in android

PFB code. DB connection is success but when try to register with register.php script in my android phone getting error page or getting please fill all values. I am not getting success. Kindly help. I am also using the URL register url in my java code as well http://xxxx/Userregistration/register.php.
register.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if ($name == '' || $username == '' || $password == '' || $email == '') {
echo 'please fill all values';
} else {
require_once('dbConnect.php');
$sql = "SELECT * FROM KumbhaApp WHERE username='$username' OR email='$email'";
$check = mysqli_fetch_array(mysqli_query($con, $sql));
if (isset($check)) {
echo 'username or email already exist';
} else {
require_once('dbConnect.php');
$sql = "INSERT INTO KumbhaApp (name,username,password,email) VALUES('$name','$username','$password','$email')";
}
}
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
} else {
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Invalid email format";
}
}
if (mysqli_query($con, $sql)) {
echo 'successfully registered';
header('Location: securedpage.php');
} else {
echo 'oops! Please try again!';
}
mysqli_close($con);
}
?>
It is not required, it is require. Your code
required ("http://localhost:8080/UserRegistration/dbConnect.php");
^
is wrong.

PHP doesn't work properly when hosted

I have made a Log in and Sign up system and on my localhost it worked properly but when i hosted it and created account it says Incorrect credentials. I will send a code if it is needed. And i have crated a MySql db.
Site link: http://metallicafanpage.esy.es
I am using Hostinger
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: home.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($email)){
$error = true;
$emailError = "Please enter your email address.";
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT userId, userName, userPass FROM users WHERE userEmail='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['userId'];
header("Location: home.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
Here is Register.php
<?php
ob_start();
session_start();
if( isset($_SESSION['user'])!="" ){
header("Location: home.php");
}
include_once 'dbconnect.php';
$error = false;
if ( isset($_POST['btn-signup']) ) {
// clean user inputs to prevent sql injections
$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);
// basic name validation
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.";
}
//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
// check email exist or not
$query = "SELECT userEmail FROM users WHERE userEmail='$email'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have atleast 6 characters.";
}
// password encrypt using SHA256();
$password = hash('sha256', $pass);
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO users(userName,userEmail,userPass) VALUES('$name','$email','$password')";
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($name);
unset($email);
unset($pass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>
This Is Because Of Your Php Mysql version Your Hosting Server Is Just Using An Old Php Or Mysql Version

Categories