Persistent login after user's signing up and confirms their accounts through email, and after they log in - php

I'm creating an authentication system based on a token generated in PHP, that the user has to confirm their account through an email sent to them after signing up, and the token is validated after the user clicks on the link that is supposed to process the PHP page responsible for token and then to a Thank you for confirmation page, but instead, they're redirected to the login page, and that also happens with the other pages, even though I set up session_start in the backend.
Down below you can see the code snippets of signup/login.php, Signup/Login.js, confirm_account.php, and AccountConfirmed.js
SignUp.js
const SignUp = () => {
const navigate = useNavigate();
const [first_name, setFirstName] = useState("");
const [last_name, setLastName] = useState("");
const [company, setCompany] = useState("");
const [email, setEmail] = useState("");
const [phone_number, setPhoneNumber] = useState("");
const [password, setPassword] = useState("");
const [confirm_password, setConfirmPassword] = useState("");
const [errorMessage, setErrorMessage] = useState("");
function emailValidation() {
const emailRegex =
/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]#(gmail|hotmail|outlook|yahoo)\.com\b$/g;
return emailRegex.test(email);
}
const handleSignUpSubmit = (event) => {
event.preventDefault();
const register_account = {
first_name: first_name,
last_name: last_name,
company: company,
email: email,
phone_number: phone_number,
password: password,
confirm_password: confirm_password,
};
axios
.post("http://localhost/bachelor_exam/signup.php", register_account)
.then((response) => {
if (response.data) {
navigate("/emailconfirm");
}
})
.catch((error) => {
if (
error.response &&
error.response.data === "All fields must be filled in"
) {
setErrorMessage("All fields must be filled in");
} else if (
error.response &&
error.response.data ===
"The first name must be longer than 2 characters"
) {
setErrorMessage("The first name must be longer than 2 characters");
} else if (
error.response &&
error.response.data ===
"The first name cannot be longer than 12 characters"
) {
setErrorMessage("The first name cannot be longer than 12 characters");
} else if (
error.response &&
error.response.data ===
"The last name must be longer than 2 characters"
) {
setErrorMessage("The last name must be longer than 2 characters");
} else if (
error.response &&
error.response.data ===
"The last name cannot be longer than 12 characters"
) {
setErrorMessage("The last name cannot be longer than 12 characters");
} else if (
error.response &&
error.response.data === "The email is not valid" &&
!emailValidation()
) {
setErrorMessage("The email is not valid");
} else if (
error.response &&
error.response.data === "The password is not strong enough"
) {
setErrorMessage("The password is not strong enough");
} else if (
error.response &&
error.response.data ===
"The password has exceeded the maximum of characters"
) {
setErrorMessage(
"The password has exceeded the maximum of characters"
);
} else if (
error.response &&
error.response.data === "Danish phone number must be provided"
) {
setErrorMessage("Danish phone number must be provided");
} else if (
error.response &&
error.response.data === "The passwords does not match"
) {
setErrorMessage("The passwords does not match");
} else if (
error.response &&
error.response.data === "The email has already been registered"
) {
setErrorMessage("The email has already been registered");
} else if (
error.response &&
error.response.data === "The phone number has already been registered"
) {
setErrorMessage("The phone number has already been registered");
} else {
console.log(error);
}
});
};
Login.js
const Login = () => {
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [errorMessage, setErrorMessage] = useState("");
function emailValidate() {
const emailRegex =
/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]#(gmail|hotmail|outlook|yahoo)\.com\b$/g;
return emailRegex.test(email);
}
const handleLogInSubmit = (event) => {
event.preventDefault();
const logged_in = {
email: email,
password: password,
};
axios
.post("http://localhost/bachelor_exam/login.php", logged_in)
.then((response) => {
if (response.data) {
const userData = response.data;
sessionStorage.setItem("user", JSON.stringify(userData));
navigate("/dashboard");
} else {
setErrorMessage(response.data);
}
})
.catch((error) => {
if (
error.response &&
error.response.data === "All fields must be filled in"
) {
setErrorMessage("All fields must be filled in");
} else if (
error.response &&
error.response.data === "The email is not valid" &&
!emailValidate()
) {
setErrorMessage("The email is not valid");
} else if (
error.response &&
error.response.data === "All fields must be filled in"
) {
setErrorMessage("All fields must be filled in");
} else if (
error.response &&
error.response.data === "The password is not strong"
) {
setErrorMessage("The password is not strong");
} else if (
error.response &&
error.response.data ===
"The password has reached the maximum characters"
) {
setErrorMessage("The password has reached the maximum characters");
} else if (
error.response &&
error.response.data === "Wrong email or password"
) {
setErrorMessage("Wrong email or password");
} else if (
error.response &&
error.response.data === "User does not exist"
) {
setErrorMessage("User does not exist");
} else {
console.log(error);
}
});
};
Signup and Login.php
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
require_once (__DIR__."/globals.php");
session_start();
$data = file_get_contents("php://input");
if (isset($data) && !empty($data)){
$request = json_decode($data);
$firstName = $request->first_name;
$lastName = $request->last_name;
$company = $request->company;
$email = $request->email;
$phoneNumber = $request->phone_number;
$password = $request->password;
$confirmPassword = $request->confirm_password;
if(empty($firstName) || empty($lastName) || empty($company) || empty($email) ||
empty($password) || empty($confirmPassword)){
http_response_code(400);
echo json_encode("All fields must be filled in");
exit();
}
if(strlen($firstName) < _NAME_MIN_LEN){
http_response_code(400);
echo json_encode("The first name must be longer than 2 characters");
exit();
}
if(strlen($firstName) > _NAME_MAX_LEN){
http_response_code(400);
echo json_encode("The first name cannot be longer than 12 characters");
exit();
}
if(strlen($lastName) < _NAME_MIN_LEN){
http_response_code(400);
echo json_encode("The last name must be longer than 2 characters");
exit();
}
if(strlen($lastName) > _NAME_MAX_LEN){
http_response_code(400);
echo json_encode("The last name cannot be longer than 12 characters");
exit();
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
http_response_code(400);
echo json_encode("The email is not valid");
exit();
}
if(strlen($password) < _PASSWORD_MIN_LEN){
http_response_code(400);
echo json_encode("The password is not strong enough");
exit();
}
if(strlen($password) > _PASSWORD_MAX_LEN){
http_response_code(400);
echo json_encode("The password has exceeded the maximum of characters");
exit();
}
if(strlen($phoneNumber) !== 8){
http_response_code(400);
echo json_encode("Danish phone number must be provided");
exit();
}
if($password !== $confirmPassword){
http_response_code(400);
echo json_encode("The passwords does not match");
exit();
}
$db = _db();
try {
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$token = bin2hex(random_bytes(16));
$forgotPass = bin2hex(random_bytes(16));
$q = $db->prepare("SELECT * FROM users WHERE email = :email");
$q->bindValue(":email", $email);
$q->execute();
if($q->rowCount() > 0){
header("Content-type: application/json");
http_response_code(400);
echo json_encode("The email has already been registered");
exit();
} else {
$q = $db->prepare("SELECT * FROM users WHERE phone_number = :phone_number");
$q->bindValue(":phone_number", $phoneNumber);
$q->execute();
if($q->rowCount() > 0){
header("Content-type: application/json");
http_response_code(400);
echo json_encode("The phone number has already been registered");
exit();
} else {
$q=$db->prepare("INSERT INTO users(user_id, first_name, last_name, company,
email, phone_number, password, forgot_password, token, verified) VALUES(:user_id,
:first_name, :last_name, :company, :email, :phone_number, :password,
:forgot_password,
:token, :verified)");
$q->bindValue(":user_id", null);
$q->bindValue(":first_name", $firstName);
$q->bindValue(":last_name", $lastName);
$q->bindValue(":company", $company);
$q->bindValue(":email", $email);
$q->bindValue(":phone_number", $phoneNumber);
$q->bindValue(":password", $passwordHash);
$q->bindValue(":forgot_password", $forgotPass);
$q->bindValue(":token", $token);
$q->bindValue(":verified", false);
$q->execute();
$id = $db->lastInsertId();
$to_email = $email;
$subject = "Nuub - Account Confirmation";
$message = "Welcome to Nuub, click on the following link to verify your account:
<a href='http://localhost/bachelor_exam/confirm_account.php?
token=$token'>Confirm your account</a>";
require_once(__DIR__."/emailVerification/send_email.php");
$_SESSION["first_name"] = $firstName;
header("Content-type: application/json");
http_response_code(200);
echo json_encode($_SESSION["first_name"]);
exit();
}
}
} catch (Exception $ex){
header("Content-type: application/json");
http_response_code(500);
echo json_encode("System not working");
echo "Debug info: " . $ex->getMessage();
exit();
}
}
/// LOGIN ///
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
require_once (__DIR__."/globals.php");
session_start();
$data = file_get_contents("php://input");
if (isset($data) && !empty($data)) {
$request = json_decode($data);
$email = $request->email;
$passwordCheck = $request->password;
// empty input
if (empty($email) || empty($passwordCheck)){
http_response_code(400);
echo json_encode("All fields must be filled in");
exit();
}
// email validation
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
http_response_code(400);
echo json_encode("The email is not valid");
exit();
}
// password validation
else if (strlen($passwordCheck) < _PASSWORD_MIN_LEN){
http_response_code(400);
echo json_encode("The password is not strong");
exit();
}
else if (strlen($passwordCheck) > _PASSWORD_MAX_LEN){
http_response_code(400);
echo json_encode("The password has reached the maximum characters");
exit();
}
$db = _db();
try {
$q=$db->prepare("SELECT * FROM users WHERE email = :email");
$q->bindValue(":email", $email);
$q->execute();
$row = $q->fetch();
if($q->rowCount() > 0){
if (password_verify($passwordCheck, $row["password"])) {
$_SESSION["user_id"] = $row["user_id"];
$_SESSION["first_name"] = $row["first_name"];
$_SESSION["last_name"] = $row["last_name"];
$_SESSION["email"] = $row["email"];
$_SESSION["company"] = $row["company"];
$_SESSION["phone_number"] = $row["phone_number"];
$_SESSION["verified"] = $row["verified"];
$_SESSION["token"] = $row["token"];
$_SESSION["forgot_password"] = $row["forgot_password"];
http_response_code(200);
echo json_encode($_SESSION["user_id"]);
exit();
} else {
http_response_code(400);
echo json_encode("Wrong email or password");
exit();
}
} else {
http_response_code(400);
echo json_encode("User does not exist");
exit();
}
} catch(Exception $ex){
http_response_code(500);
echo json_encode("System not working");
echo "Debug info:" . $ex->getMessage();
}
}
confirm_account.php
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
require_once (__DIR__."/globals.php");
session_start();
$db = _db();
try {
$token = $_GET["token"];
$q=$db->prepare("UPDATE users SET verified = :verified WHERE token = :token");
$q->bindValue(":token", $token);
$q->bindValue("verified", true);
$q->execute();
$q->rowCount();
header("Location: http://localhost:3000/accountconfirmed");
echo json_encode("Success");
exit();
if($q->rowCount() > 0){
$new_token = bin2hex(random_bytes(16));
$id = $_SESSION["user_id"];
$new_q = $db->prepare("UPDATE users SET token = :token WHERE user_id = :user_id");
$new_q->bindValue(":user_id", $id);
$new_q->bindValue(":token", $new_token);
$new_q->execute();
echo json_encode("New token has been assigned");
} else {
echo json_encode("Something went wrong");
}
}catch (Exception $ex){
header("Content-type: application/json");
http_response_code(500);
echo json_encode(["error" => $ex->getMessage()]);
exit();
}
AccountConfirmed.js
const AccountConfirmed = () => {
const navigate = useNavigate();
const { search } = useLocation();
const [validToken, setValidToken] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
useEffect(() => {
const params = new URLSearchParams(search);
const token = params.get("token");
if(token){
axios.get(`http://localhost/bachelor_exam/confirm_account.php?token=${token}`)
.then((response) => {
if(response.data === "Success"){
sessionStorage.setItem("token", token);
setValidToken(true);
} else {
setErrorMessage(response.data);
}
})
.catch((error) => {
console.log(error);
})
} else {
navigate("/login");
}
}, [navigate, search]);
My apologies for a load of code, and I'm using Reactjs as frontend.

Related

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 to get the ID of a logged in user php

Hi I'm relatively new to php and I'm making a booking system database and website using php,and phpmyadmin as a server. I need help with coding of the database.
Specifically I'm trying to get the id of a logged in user.
here is my code
// connect to database
$db = mysqli_connect('localhost', '#', '#', '#'); // hidden for security
// variable declaration
$username = "";
$email = "";
$errors = array();
// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
register();
}
// call the login() function if register_btn is clicked
if (isset($_POST['login_btn'])) {
login();
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['user']);
header("location: login.php");
}
if (isset($_POST['pickup_date'])) {
book();
}
// REGISTER USER
function register(){
global $db, $errors;
// receive all input values from the form
$firstname = e($_POST['firstname']);
$surname = e($_POST['surname']);
$address = e($_POST['address']);
$home_postcode = e($_POST['home_postcode']);
$age = e($_POST['age']);
$email = e($_POST['email']);
$username = e($_POST['username']);
$password_1 = e($_POST['password_1']);
$password_2 = e($_POST['password_2']);
// form validation: ensure that the form is correctly filled
if (empty($firstname)) {
array_push($errors, "first name is required");
}
if (empty($surname)) {
array_push($errors, "surname is required");
}
if (empty($address)) {
array_push($errors, "address is required");
}
if (empty($home_postcode)) {
array_push($errors, "home postcode is required");
}
if (empty($age)) {
array_push($errors, "age is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
$password = $password_1;
// register user if there are no errors in the form
if (count($errors) == 0) {
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO users (firstname, surname, address, home_postcode, age, email, username, user_type, password)
VALUES('$firstname', '$surname', '$address', '$home_postcode','$age','$email', '$username', '$user_type', '$password')";
mysqli_query($db, $query);
$_SESSION['success'] = "New user successfully created.";
header('location: home.php');
}else{
$query = "INSERT INTO users (firstname, surname, address, home_postcode, age, email, username, user_type, password)
VALUES('$firstname', '$surname', '$address', '$home_postcode','$age','$email', '$username', 'user', '$password')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
}
// BOOK A CAR
function book() {
global $db, $errors;
// receive all input values from the form
$car_chosen = e($_POST['car_chosen']);
$pickup_date = e($_POST['pickup_date']);
$pickup_time = e($_POST['pickup_time']);
$return_date = e($_POST['return_date']);
$return_time = e($_POST['return_time']);
$collection_postcode = e($_POST['collection_postcode']);
// form validation: ensure that the form is correctly filled
if (empty($pickup_date)) {
array_push($errors, "pickup date is required");
}
if (empty($pickup_time)) {
array_push($errors, "pickup time is required");
}
if (empty($return_date)) {
array_push($errors, "return date is required");
}
if (empty($return_time)) {
array_push($errors, "return time is required");
}
if (empty($collection_postcode)) {
array_push($errors, "collection postcode is required");
}
// convert car chosen to the ID of that car
$query = "SELECT * FROM cars WHERE car_ID = " . $car_chosen;
// book car if there are no errors in the form
if (count($errors) == 0) {
$query = "INSERT INTO booking_details (pickup_date, pickup_time, return_date, return_time, total_cost, collection_postcode, car_fk, user_fk)
VALUES('$pickup_date', '$pickup_time', '$return_date', '$return_time', '1000', '$collection_postcode','$car_chosen','$id')";
if(mysqli_query($db, $query)){
echo 'hello';
}else{
echo "<br>" . $query . "<br>";
echo mysqli_error($db);
}
}
}
// return user array from their id
function getUserById($id){
global $db;
$query = "SELECT * FROM users WHERE user_id=" . $id;
$result = mysqli_query($db, $query);
$user = mysqli_fetch_assoc($result);
return $user;
}
// LOGIN USER
function login(){
global $db, $username, $errors;
// grab form values
$username = e($_POST['username']);
$password = e($_POST['password']);
// make sure form is filled properly
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
// attempt login if no errors on form
if (count($errors) == 0) {
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: home.php');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
function isAdmin()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
return true;
}else{
return false;
}
}
// escape string
function e($val){
global $db;
return mysqli_real_escape_string($db, trim($val));
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
so I need to have the id of the user collected once they log in. I also need it to work where the user is logged in after registering for the first time.
And I have no idea how to get it, I've only managed to get the ID of the car chosen. Once the user_id is collected I should be able to insert it into the booking_details table with the rest of the values.
everything else works fine.
thank you all the help is appreciated.
You should get user details from session
$user = $_SESSION['user'];
$loggeduserid = $user['id'];
Note : here id is column name of user table
You are dumping an entire row (array) of data into $session['user']
$logged_in_user = mysqli_fetch_assoc($results);
$_SESSION['user'] = $logged_in_user;
Therefore you should simply be able to get the ID of the logged-in user using the ID column name.
$loggedInUserId = $_SESSION['user']['name_of_id_column'];
Finally, I should say it plainly. You are not using SQL in a safe manner. As the commenters have suggested, look into PDO and prepared statements. It is easier than you think. https://phpdelusions.net/pdo

Is this possible to send response back to page by doing some if/else in ajax

I want to know that is this possible to send response back by using some if/else on response we get from server under success in $.ajax..
ajax
$.ajax({
url : "request/register.php",
type : "POST",
data : 'firstName='+firstName + '&lastName='+lastName + '&userName='+userName + '&email='+email + '&password='+password + '&con_password='+con_password,
dataType : "text",
beforeSend : function(http){
$('#reg').val("Submitting....");
},
success : function(response,status,http){
var text = response;
alert(text);
if(text != "<span class=\"error\" data-icon =''>Empty Fields</span>"){
alert("Done");
}else{
alert("oOps")
}
},
error : function(http,status,error){
alert('server error');
}
})
registeration.php
//creating a variable for error messages
$error = "";
//creating a variable for success messages
$success = "";
//form validation
if($_SERVER['REQUEST_METHOD'] == "POST"){
$firstName = trim(filter_input(INPUT_POST, 'firstName' ,FILTER_SANITIZE_STRING));
$lastName = trim(filter_input(INPUT_POST, 'lastName' ,FILTER_SANITIZE_STRING));
$userName = trim(filter_input(INPUT_POST, 'userName' ,FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST, 'email' ,FILTER_SANITIZE_EMAIL));
$password = trim(filter_input(INPUT_POST, 'password' ,FILTER_SANITIZE_STRING));
$confirm_pass = trim(filter_input(INPUT_POST, 'con_password' ,FILTER_SANITIZE_STRING));
//checking for empty feilds
if($firstName == "" || $lastName == "" || $userName == "" || $email == "" || $password == "" || $confirm_pass == ""){
$error = "Empty Fields";
}
//checking username length
if(empty($error) && strlen($userName)<=5){
$error = "Username must be greater than 5 characters";
}
//checking for username existence
if(empty($error) && user_exist($userName)){
$error = "Username already exist";
}
//email validation
if(empty($error) && !filter_var($email,FILTER_VALIDATE_EMAIL)){
print_r($_POST);
$error = "Invalid Email address";
}
//checking for email existence
if(empty($error) && email_exist($email)){
$error = "Email already exist";
}
//checking password length
if(empty($error) && strlen($password)<=8){
$error = "Password must be greater than 8 characters";
}
//matching confirm password
if(empty($error) && $password !== $confirm_pass){
$error = "Password not match";
}
if(empty($error)){
if(user_registration($firstName,$lastName,$userName,$email,md5($password))){
$success = "Registered Suceessfully";
}else{
$error = "Something went wrong";
}
}
}
if(!empty($error)){
echo "<span class=\"error\" data-icon =''>".$error."</span>";
}
if (empty($error) && !empty($success)) {
echo "<span class=\"success\" data-icon =''>".$success."</span>";
}
If response is something like than i want to set input[type="text"] values should be same what user type and input[type="password"] should be blank & in other case if response is something like i want all the input feilds empty..
Yes, it's possible. But as the body may change overtime, it's best to do your if/else logic on the HTTP/1.1 Status Codes.
For example;
In your error response, simply return an error code 400 Bad Request by using http_response_code()
http_response_code(400);
And in your success response, simply return a 201 Created
http_response_code(201);
Now, in your jQuery, you can just look at the return status code and do the appropriate thing for the end-user
//[...]
success : function(response,status,http) {
if(http.status === 201) {
alert("User created");
} else {
//Assume there was an error
//Do some error logging for the end-user
alert("Could not create the user");
}
}

User Add/login form Issue

I made a simple User Add/login form .But i cannot extract or add data to database using array and need simple procedure.
<?php
//User_Add_Page
if(isset($_POST['userid'],$_POST['username'],$_POST['password'],$_POST['sex'],$_POST['desig']))
{
include("connect.php");
$badchars='!#£$%^&*()+=-][\;/.,`~<>?:"|{} \'';
$userid=$_POST['userid'];
$username=$_POST['username'];
$password=$_POST['password'];
$sex=$_POST['sex'];
$desig=$_POST['desig'];
$errors=array();
if(empty($userid)&& empty($username) && empty($password) && empty($sex) && empty($design))
{
$errors[]= "All Fields Require";
}
else if($userid=="")
{
$errors[]= "Enter User ID";
}
else if (strpbrk($userid, $badchars) !== false)
{
$errors[]= 'INVALID User ID...';
}
else if(strlen($userid)<5 && $username != "")
{
$errors[]='User ID Must be Greater than 5 Characters';
}
else if(is_numeric ($userid))
{
$errors[]= 'User ID Must Conatin Both letters AND character';
}
else if(strlen($userid)>20 && $username != "")
{
$errors[]= 'User ID Must be Less Than 20 Characters';
}
else if($username=="")
{
$errors[]= "Enter username";
}
else if(strlen($username)>30)
{
$errors[]= "Enter username less than 30 char.";
}
else if(!ctype_alpha(str_replace(' ','',$username)))//search alphabetic char. from username
{
$errors[]='Name Must be Character Only';
}
else if($password == "")
{
$errors[]= 'Please Enter Password';
}
else if(strlen($password)<5 && $password != "")
{
$errors[]= 'Password Must Be Greater Than 5 Characters';
}
else if($desig == "")
{
$errors[]= 'Please Enter Designation';
}
else if(empty($errors))
{
$write=("INSERT INTO adduser VALUES ('','$userid','$username','$password','$sex','$desig')");
$time = 1; //Time (in seconds) to wait.
$url = "add_user_process.php"; //Location to send to.
header("Refresh: $time; url=$url");
}
}
?>
else if(empty($errors))
{
$write=("INSERT INTO adduser VALUES ('','$userid','$username','$password','$sex','$desig')");
mysqli_query($write,Your_connection_string)
$time = 1; //Time (in seconds) to wait.
$url = "add_user_process.php"; //Location to send to.
header("Refresh: $time; url=$url");
}
After your "INSERT INTO" you have to specify mysql_query object ,
like $result = mysql_query($write);
Like this ,
$write="INSERT INTO adduser VALUES ('','$userid','$username','$password','$sex','$desig')";
$result = mysql_query($write);

Issue with Form and PDO

I plan to clean up the code, and make it more OOP friendly later, but for now I am struggling to get this to work. I have managed to get down for it to echo 'hi', but the execute doesn't seem to be putting anything into the database, and it is not giving me any errors. The code is
public function newAccount(array $data) {
$error = NULL;
//Check first name length, and make sure its over 2 characters
if (strlen($data['fname']) > 2) {
$fname = $data['fname'];
}
else {
$fname = FALSE;
$error .= "Please put in a valid First Name. <br />";
}
//Check if last name length is over 2 characters
if (strlen($data['lname']) > 2) {
$lname = $data['lname'];
}
else {
$lname = FALSE;
$error .= "Please enter a valid Last Name. <br />";
}
// Check username
if (strlen($data['user']) > 3) {
$user = $data['user'];
}
else {
$user = FALSE;
$error .= "Username must be longer than 3 characters.<br />";
}
// Mske sure password is atleast 6 characters, and retyped correctly
if (strlen($data['pass']) > 5) {
if ($data['pass'] == $data['repass']) {
$pass = $data['pass'];
}
else {
$pass = FALSE;
$error .= "Passwords do not match.<br />";
}
}
else {
$pass = FALSE;
$error .= "Password must be longer than 6 characters.";
}
//make sure email looks correct, strpos makes sure there is an '#'
if (strlen($data['email']) > 5 && strpos($data['email'], '#')) {
$email = $data['email'];
}
else {
$email = FALSE;
$error .= "Please enter a valid email. <br />";
}
// Check if user is suppose to be admin
if (isset($data['admin'])) {
$admin = '1';
}
else {
$admin = '0';
}
if ($fname && $lname && $user && $pass && $email) {
echo 'hi';
try {
$sth = $this->dbc->prepare("INSERT INTO users(user, password first_name, last_name, email, admin) VALUES(:user, MD5(:pass), :fname, :lname, :email, :admin)");
$sth->execute(array(":user" => $user,
":pass" => $pass,
":fname" => $fname,
":lname" => $lname,
":email" => $email,
":admin" => $admin)
);
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
else {
echo "Error" . $error;
}
}
Thanks in advance!
In your insert query, you are missing a comma after password field.
It should be
$sth = $this->dbc->prepare("INSERT INTO
users(user, password, first_name, last_name, email, admin)
VALUES(:user, MD5(:pass), :fname, :lname, :email, :admin)");
Also, when testing is entered string is email address or not, use filter_var(). Like this:
if( filter_var($data['email'], FILTER_VALIDATE_EMAIL) {
//do this...

Categories