Redirect losing POST/SESSION DATA - javascript

I have a problem with redirection, my whole code is working my only problem is losing a POST/SESSION data in the process. spent countless hours working with it and try alot of work arounds, but still it does not work and that is my only problem. here's my code
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This variable will be used to re-display the user's username to them in the
// login form if they fail to enter the correct password. It is initialized here
// to an empty value, which will be shown if the user has not submitted the form.
// This if statement checks to determine whether the login form has been submitted
// If it has, then the login code is run, otherwise the form is displayed
if(!empty($_POST)) {
// This query retreives the user's information from the database using
// their username.
if(isset($_POST['validEmail'])) {
$query = "SELECT *
FROM registered_email
WHERE email = :validEmail";
}
// The parameter values
$query_params = array( ':validEmail' => $_POST['validEmail'] );
try {
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query");
}
// This variable tells us whether the user has successfully logged in or not.
// We initialize it to false, assuming they have not.
// If we determine that they have entered the right details, then we switch it to true.
$login_ok = false;
// Retrieve the user data from the database. If $row is false, then the username
// they entered is not registered.
$row = $stmt->fetch();
if($row) {
if($_POST['validEmail'] === $row['email']) {
// If they do, then we flip this to true
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok) {
$_SESSION['sesEmail'] = $row;
// Redirect the user to the private members-only page.
if (isset($_POST['validEmail'])) {
echo "<script>location='http://www.url.com.ph/some.php'</script>";
}
} else {
// Tell the user they failed
print "Sorry to say that your Email is not Registered!.";
}
}

Ideally your code should look something like this, it should work fine as far as I see. I refactored your code and edited the redirect statement.
// I am assuming you have session_start(); included in common.php
require("common.php");
if(!empty($_POST)) {
if(isset($_POST['validEmail'])) {
$query = "SELECT *
FROM registered_email
WHERE email = :validEmail";
$query_params = array( ':validEmail' => $_POST['validEmail'] );
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
die("Failed to run query");
}
$login_ok = false;
$row = $stmt->fetch();
if($row) {
if($_POST['validEmail'] === $row['email']) {
$login_ok = true;
}
}
if($login_ok) {
$_SESSION['sesEmail'] = $row;
if (isset($_POST['validEmail'])) {
// the page where you are redirecting should be linked with session as well
echo "<script>window.location.href='http://www.url.com.ph/some.php'</script>";
}
} else {
// Tell the user they failed
print "Sorry to say that your Email is not Registered!.";
}
}
else {
// Tell the user they failed
print "Sorry no POST parameters!.";
}
}
Hope it helps. If not feel free to discuss.

Related

How to solve javascript not redirecting after google signin?

I'm trying to implement Google Signin onto my site. How can I redirect users to logged in members page?
I'm now able to verify the token, after the verification, user should be redirected to loggedin members page, I've tried to use javascript to do so, but it seems to be not working.
I've tried manually type the javascript in the console, login is successful.
<?php
...
require_once 'vendor/autoload.php';
$client = new Google_Client();
$client->setScopes('email');
$payload = $client->verifyIdToken($id_token);
if ($payload == true) {
$userid = $payload['sub'];
//check user existance
if ($check_googleuser_result->num_rows == 1) {
$_SESSION['loggedin_userlogin'] = $email;
//redirect user
echo '<script>window.location = "loggedin.php";</script>';
} else {
echo 'No matched user';
//signout user
echo '<script>location.replace("gsignout.php");</script>';
}
} else {
echo 'error';
//signout user
echo '<script>location.replace("gsignout.php");</script>';
}
?>
Expected to redirect the user after successful check existence of user.
Actual output is that the session is created, but javascript not performing redirection.
UPDATE:Screenshot of background1
Screenshot of background2
As you are trying to redirect in your php code, you should also use the php provided functions for that.
For this there is a function called header()
So your code would look like this:
<?php
...
require_once 'vendor/autoload.php';
$client = new Google_Client();
$client->setScopes('email');
$payload = $client->verifyIdToken($id_token);
if ($payload == true) {
$userid = $payload['sub'];
//check user existance
if ($check_googleuser_result->num_rows == 1) {
$_SESSION['loggedin_userlogin'] = $email;
//redirect user
header('Location: loggedin.php');
} else {
echo 'No matched user';
//signout user
header('Location: gsignout.php');
}
} else {
echo 'error';
//signout user
header('Location: gsignout.php');
}
?>

My registration code is allowing the same email to register twice (only when the form is submitted multiple times in a row very fast) [duplicate]

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 6 years ago.
I have written some registration code with HTML, Javascript and php.
The registration process(at a higher level) is as follows:
The user:
1. Enters their email, name, and password(twice) to an HTML form.
2. They press "create account"
3. Their email is then searched for in my users table to see if it
exists.
4. If it exists then they are told they are already registered and provided with a link to the login screen.
5. If the email doesn't already exist then it is inserted (along with other user details) to the users table in my database
My code works well to achieve this, however on testing it I have found a fault. If the user presses "create account" multiple times very fast it allows the same email address to register twice. Is there anything I can do to stop this?
Here's my code:
JQuery/Javascript
$("#registration_form").on("submit", function(e){
//this is called when the form is submitted i.e when "create account" is pressed
e.preventDefault();
var registration_email = $('#registration_email').val();
var registration_password = $('#registration_password').val();
var registration_password_confirmation = $('#confirm_registration_password').val();
var registration_display_name = $('#registration_display_name').val();
//validate fields and check if passwords match.
//all values have passed validation testing therefore make ajax request
var params = { 'registration_email' : registration_email, 'registration_password' : registration_password , 'registration_display_name' : registration_display_name, 'app_root_url':app_root_url};
$.ajax({
url: app_root_url + 'login_registration/registration_processing.php',
data: JSON.stringify(params),
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
success: function(data){
var result = data;
var emailAlreadyExists = result.email_already_exists;
if(emailAlreadyExists){
//email already exists in our database and therefore the user is already registered so should use the login form
displayError('registration_feedback_message', 'This email already exists in the system. If you already have an account please login here!');
}else{
//email does not already exist in our database
}
}//end success
});//end ajax
});
registration_processing.php (the main part of this file)
include_once '../includes/app_functions.php';
$app_root_url = filter_var($json->app_root_url, FILTER_SANITIZE_URL);
$email = filter_var($json->registration_email, FILTER_SANITIZE_EMAIL);
$password = filter_var($json->registration_password, FILTER_SANITIZE_STRING);
$display_name = filter_var($json->registration_display_name, FILTER_SANITIZE_STRING);
//more data filtering is performed here
$userPrivilegeID = 1; //basic user privilege
$userHasPassword = 1; //boolean 1 or 0
$profileImage = "images/profile_images/blank-avatar.png";
$results = registerUser($password, $email, $isAvatarImage, $profileImage, $userPrivilegeID, $display_name, $userHasPassword, $pdoConnection);
//create an array to store all values that we want to send back to the client side.
$data = array();
if($results['exception_occurred'] == true){
$data['exception_occurred'] = true;
$data['exception_message'] = $results['exception_message'];
echo json_encode($data);
}else{
$data['exception_occurred'] = false;
if($results['email_already_exists'] == true){
//email already exists. user is already registered and therefore has a password
//need to show error to user to say they are already registered and should use the login form.
$data['email_already_exists'] = true;
echo json_encode($data);
}else{
//email didnt exist so they have been registered
$data['email_already_exists'] = false;
//create an array which we will encrypt as our JWT token
$token = array();
$token['userID'] = $results['user_id'];
$token['email'] = $email;
$data['userID'] = $results['user_id'];
$data['user_is_subscriber'] = true;
$data['valid_user'] = true;
$data['userDetails'] = getProfile($results['user_id'], $pdoConnection);
$data['usertoken'] = JWT::encode($token, 'secret_server_key');
//echo data back to ajax request on client side
echo json_encode($data);
}
}
registerUser function (in app_functions.php)
function registerUser($password, $email, $isAvatarImage, $profileImage, $userPrivilegeID, $display_name, $userHasPassword, $pdoConnection){
$data = array();
try{
$data['exception_occurred'] = false;
//first check if that email already exists just in case
$query = "SELECT COUNT(userID) FROM users WHERE emailAddress=:emailAddress";
$statement = $pdoConnection->prepare($query);
$statement->bindValue(':emailAddress', $email, PDO::PARAM_STR);
$statement->execute();
$rowCount = $statement->fetchColumn(0);
if($rowCount > 0){
//email already exists. user is already registered and therefore has a password
//need to show error to user to say they are already registered and should use the login form.
$data['email_already_exists'] = true;
return $data;
}else{
$data['email_already_exists'] = false;
$hashedPassword = password_hash($password, PASSWORD_DEFAULT, ['cost' => 12]);
$query = "INSERT INTO users (emailAddress, password, isAvatarImage, profileImage, userPrivilegeID, displayName, userHasPassword) VALUES (:emailAddress, :password, :isAvatarImage, :profileImage, :userPrivilegeID, :displayName, :userHasPassword)";
$statement = $pdoConnection->prepare($query);
$statement->bindValue(':emailAddress', $email, PDO::PARAM_STR);
$statement->bindValue(':password', $hashedPassword, PDO::PARAM_STR);
$statement->bindValue(':isAvatarImage', $isAvatarImage, PDO::PARAM_INT);
$statement->bindValue(':profileImage', $profileImage, PDO::PARAM_STR);
$statement->bindValue(':userPrivilegeID', $userPrivilegeID, PDO::PARAM_INT);
$statement->bindValue(':displayName', $display_name, PDO::PARAM_STR);
$statement->bindValue(':userHasPassword', $userHasPassword, PDO::PARAM_INT);
$statement->execute();
$data['user_id'] = $pdoConnection->lastInsertId();
return $data;
}
}catch(PDOException $e){
//throw new pdoDbException($e);
$data['exception_occurred'] = true;
$data['exception_message'] = $e->getMessage();
return $data;
}
}
One solution I can think of is to put a timer on the "create account" button so that multiple ajax requests can't be made so close together?
Edit
After reading some of your solutions I am looking into making the email field unique. thanks
I am working in phpMyAdmin so is it as simple as just pressing "unique"(highlighted in the image)?
Edit 2
I tried creating the email as a unique key and i get the following error:
Edit 3
To solve the error above (in Edit 2) I changed the collation of the email address field from utf8mb4_unicode_ci to utf8_unicode_ci and then I tried pressing "unique" again and it worked. Thank you all
You may add UNIQUE CONSTRAINT to your email field into the database. This way if you try to insert an email that already exists, it fails.
Make the email field in your database unique. I don't recommend PK because users may want to change their email address.
I always recommend doing validations on both the server and the client.
In this case, as everyone mentioned, in the server (Database) you should define a unique constraint on the e-mail field, so repeated e-mails will never actually happen.
I would also recommend to disable the "Create account" button after the first click on it. You could even change the name of the button to "... please wait" to indicate the operation is being executed. When you get the response from the server (either success or failure) you can enable it again. This will avoid any unnecessary successive calls to the server in the first place.
You have returned data in else case and not in if case now there are two options.
instead of returning data in else block return it outside the else block or
return data in if case too.
This causes when it founds the email id but does not return it will be as false if you check hence it allows to register the user to use same email id for two different accounts

UIkit framework notify with php variable

I have that code
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = ({UIkit.notify('Message...');});
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password= sha1($_POST['password']);
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
include ('bd.php');
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from users where password='$password' AND username='$username'", $ligabd);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['idlogin']=$username; // Initializing Session
header("location: ../home.php"); // Redirecting To Other Page
} else {
$error = "Dados incorrectos";
}
mysql_close($ligabd); // Closing Connection
}
}
?>
I'm using uikit framework and i want to show up a notification from that framework when the user insert wrong user and pass and show that notification in the login page calling a php variable with the stored code
the code was the variable $error and the call to the notify UIkit.notify('Message...');
but in the login page if wrong user is insert nothing happens
regards in advance and sorry for my englisgh...

Page Doesn't Refresh after AJAX is successful

My page doesn't refresh when there are no errors.
I used:
window.location.reload(true);
That is supposed to be executed when data.success returns True.
I'm new to PHP and AJAX, so I'm using this as a guide. I know how to process info to server, but I want to display messages without leaving the page.
PHP:
<?php
// connects to "ajax" database
mysql_connect("localhost", "root", "password");
mysql_select_db("ajax");
// assigns variables to fields
$name = $_POST['name'];
$email = $_POST['email'];
$superheroAlias = $_POST['superheroAlias'];
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['superheroAlias']))
$errors['superheroAlias'] = 'Superhero alias is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
$sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
$query = #mysql_query($sql);
header("location: /");
}
// return all our data to an AJAX call
echo json_encode($data);
?>
JS
// magic.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'superheroAlias' : $('input[name=superheroAlias]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true,
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if (!data.success) {
// handle errors for name ---------------
if (data.errors.name) {
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#name-group').append('<div class="help-block">' + data.errors.name + '</div>'); // add the actual error message under our input
}
// handle errors for email ---------------
if (data.errors.email) {
$('#email-group').addClass('has-error'); // add the error class to show red input
$('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
}
// handle errors for superhero alias ---------------
if (data.errors.superheroAlias) {
$('#superhero-group').addClass('has-error'); // add the error class to show red input
$('#superhero-group').append('<div class="help-block">' + data.errors.superheroAlias + '</div>'); // add the actual error message under our input
}
} else {
window.location.reload(true);
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
There are many errors in your code. To begin with, the reason your AJAX call is only executed when there are errors is because you're relocating your page when there aren't any errors.
header("location: /");
Is your culprit. You're relocating the page before you can ever output any JSON. Second of all, your $data variable doesn't contain the [success] key when there is a successful $_POST transit. So even if you weren't to relocate, you still wouldn't be outputting any useful data. Third of all, you never saved a link to your MySQL database, you only instantiated it. Also, you're going to want to use mysqli_ because mysql_ is deprecated.
Change those first two lines of code to this:
$link = new mysqli( "localhost", "root", "password", "ajax" );
Change that if-statement to this:
if ( ! empty( $errors ) ) {
$data["errors"] = $errors;
$data["success"] = false;
} else {
$data["success"] = true;
$data["errors"] = $errors; // There are none, so this isn't neccessary
$sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
$link->query( $sql );
}
By the way, I hope this is for demonstration purposes only, because that is some terrible validation/sanitation. If it isn't, here are some useful links:
http://www.phpro.org/tutorials/Validating-User-Input.html -- In-depth tutorial on sanitation/validation
http://php.net/manual/en/book.mysqli.php -- Your guide to the MySQLi library.
remove header("location: /"); from your php file in else part.
I think this will redirect page so, your response is not like you want.
Here If condition fails then check for $data in else and remove header from else.
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
$sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
$query = #mysql_query($sql);
$data['success'] = false;
//header("location: /");
}
// return all our data to an AJAX call
echo json_encode($data);

Check if user exists with AJAX and PHP

I am trying to create a signup form that checks if the user exists in the database, I inserted a sample user and when I tried signing up with that user it didn't say its already been taken. What have I done wrong?
The JavaScript:
function formSubmit()
{
document.getElementById('email_valid').innerHTML = '';
var temail=document.forms["signup_form"]["temail"].value.replace(/^\s+|\s+$/g, '');
var atpos=temail.indexOf("#");
var dotpos=temail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=temail.length)
{
//alert("Not a valid e-mail address");
setTimeout(function(){document.getElementById('email_valid').innerHTML = '<br/>Email must be valid...';},1000);
var temailsub=0;
}
else
{
$.post('/resources/forms/signup/email.php',{email: temail}, function(data){
document.getElementById('email_valid').innetHTML = data;
if(data.exists){
document.getElementById('email_valid').innetHTML = '<br/>The email address you entered is already in use.';
var temailsub=0;
}else{
var temailsub=1;
}
}, 'JSON');
}
if(temailsub==1e)
{
setTimeout(function(){document.getElementById("signup_form").submit();},1000);
}
else
{
return false;
}
}
The PHP file (email.php):
<?php
header('content-type: text/json');
require_once $_SERVER['DOCUMENT_ROOT']."/resources/settings.php";
$query = $pdo->prepare("SELECT * FROM users WHERE email=:email");
$query->execute(array(
":email"=> $_POST['email']
));
echo json_encode(array('exists' => $query->rowCount() > 0));
?>
I have checked and double checked the code, I still cannot see why its not detecting that the email has already been used... what do i need to do to fix this and avoid this in the future?
The problem is that PDOStatement::rowCount() returns the number of rows affected by the last SQL statement. You are performing a SELECT so this value will always be 0. SELECT does not affect any rows. Instead you need to count the number of rows:
$query = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email=:email");
$query->execute(array(
":email"=> $_POST['email']
));
$rows = $query->fetchColumn();
echo json_encode(array('exists' => $rows);
Also from jtheman's comment above, you should replace innetHTML with innerHTML in your JavaScript.

Categories

Resources