Session variables are not being set, php sql - javascript

So my problem is that i'm trying to check if some session variables are set, and they should be, but when I check them they dont have a value.
So first of I have this HTML form that takes an Email and Password input
HTML CODE:
<form class="login_form" action="includes/process_login.php" method="POST" name="login_form">
<input type="text" placeholder="Email" name="email">
<input type="password" placeholder="Password" name="password" >
<input type="button" value="LOGIN" class="login_button" onclick="formhash(this.form, this.form.password);">
</form>
And as you can see my submit button first of all goes to a javascript that hashes the input.
JAVASCRIPT CODE:
function formhash(form, password) {
// Create a new element input, this will be our hashed password field.
var p = document.createElement("input");
// Add the new element to our form.
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
// Make sure the plaintext password doesn't get sent.
password.value = "";
// Finally submit the form.
form.submit();
}
And after it is done hashing the password it sends the form information to the target which is "includes/process_login.php"
PROCESS_LOGIN.PHP CODE:
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p']; // The hashed password.
if (login($email, $password, $mysqli) == true) {
// Login success
header('Location: ../protected_page.php');
} else {
// Login failed
header('Location: ../index.php?error=1['.$email.', '.$password.']');
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
?>
And from here it sends the $email and $password values into the function login:
FUNCTION LOGIN CODE:
function login($email, $password, $mysqli){
if($stmt = $mysqli->prepare("SELECT id, username, password FROM users WHERE email = ? LIMIT 1")){
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password);
$stmt->fetch();
if($stmt->num_rows == 1){
if(checkbrute($user_id, $mysqli) == true){
return false;
}else{
if (password_verify($password, $db_password)) {
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$db_password . $user_browser);
return true;
}else{
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
}else{
return false;
}
}
}
Now here comes part of the problem, in this code it stores a session:user_id values, session:username value and session:login_string value.
But the problem is that the session does not get stored anything.
Because when I then get redirected to the so called "protected_page.php" it then checks if these values are set or not and returns that they are not set.
THE LOGIN_CHECK CODE ( that checks if we are logged in or not)
function login_check($mysqli){
if (isset($_SESSION['user_id'],
$_SESSION['username'],
$_SESSION['login_string']
)) {
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
echo $user_id;
$user_browser = $_SERVER['HTTP_USER_AGENT'];
if ($stmt = $mysqli->prepare("SELECT password
FROM users
WHERE id = ? LIMIT 1")) {
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$stmt->bind_result($password);
$stmt->fetch();
$login_check = hash('sha512', $password . $user_browser);
if (hash_equals($login_check, $login_string) ){
return true;
}else{
return false;
}
}else{
return false;
}
}else{
return false;
}
}else{
return false;
}
}
Sorry about this post being very long, but I could really need some new angles. Thanks!
PS Here is the "custom set session function"
function sec_session_start(){
$session_name = 'sec_session_id';
session_name($session_name);
$secure = true;
$httponly = true;
if(ini_set('session.use_only_cookies', 1) === FALSE){
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
session_start();
session_regenerate_id(true);
}

Related

Encountering problem while posting and fetching data using php and ajax

My ajax code:
$('#name').keyup(function() {
var usercheck = $(this).val();
$('#nameAvailability').html('<img src="../SPR/assets/img/loading.gif" width="300" />'); //this part is working
$.post("../SPR/backend/username_availability_check.php", {user_name: usercheck} ,
function(data)
{
if (data.status == true)
{
$('#nameAvailability').parent('div').removeClass('has-error').addClass('has-success');
} else {
$('#nameAvailability').parent('div').removeClass('has-success').addClass('has-error');
}
$('#nameAvailability').html(data.msg); // not working
} ,'json');
});
My php code:
<?php
require("connection.php");
if(isset($_POST['user_name']) && $_POST['user_name'] != '')
{
$response = array();
$username = mysqli_real_escape_string($conn,$_POST['user_name']);
echo $username;
$sql = "select username from users where users.username='".$username."'";
$res = mysqli_query($conn, $sql);
$count = mysqli_num_rows($res);
if($count > 0)
{
$response['status'] = false;
$response['msg'] = 'Username already exists.';
}
else if(strlen($username) < 6 || strlen($username) > 15){
$response['status'] = false;
$response['msg'] = 'Username must be 6 to 15 characters';
}
else if (!preg_match("/^[a-zA-Z1-9]+$/", $username))
{
$response['status'] = false;
$response['msg'] = 'Use alphanumeric characters only.';
}
else
{
$response['status'] = true;
$response['msg'] = 'Username is available.';
}
echo json_encode($response);
echo $response;
}
?>
I have used session_start() in my index.php where user inputs his username in the input field with id 'name'
I have checked the given php code by running it individually by passing a custom username from the database and it works fine. So probably there's something wrong with the ajax code.
It is impossible to tell what your clientside code does based on what is posted here.
But in general, for debugging and to check if your serverside code works, do this:
Make a simple form, that POSTS to your PHP script.
<form action="whateveryourphpcodeisnamed.php" METHOD="POST">
<INPUT TYPE="TEXT" NAME="user_name">
<INPUT TYPE="SUBMIT" VALUE="TEST THE USERNAME">
</FORM>
And see what it says back to you.
Be sure to activate error_reporting during development.

Validate login form with JS/PHP

I want to be able to either send a user to a restricted area or return some text that says Email and or password do not exist or something similar. I'm having trouble getting this to work as whether or not the email and password are correct NOTHING happens. I'm sending the form to the index page where the script to run this sits. Not sure why I'm not redirecting or getting any kind of errors.
The restricted page checks if a $_SESSION variable isset(), if not then send them back home.
JS
loginBtn.addEventListener('click', e => {
e.preventDefault();
ajaxRequests.login(`login_email=${ loginEmail.value }&login_password=${ loginPassword.value }`);
});
ajaxRequests.login()
login(formData) {
return new Promise((resolve, reject) => {
this.xhr.open('POST', '//localhost/mouthblog/', true);
this.xhr.send(formData);
this.xhr.onload = () => {
if (this.xhr.status == 200) {
resolve();
} else {
reject(this.xhr.statusText);
}
};
this.xhr.onerror = () => {
reject(this.xhr.statusText);
};
});
}
this is the script that is supposed to run when form is sent
if (isset($_POST['login_email']) && isset($_POST['login_password'])) {
$email = htmlentities($_POST['login_email'], ENT_QUOTES, 'ISO-8859-15');
$password = htmlentities($_POST['login_password'], ENT_QUOTES, 'ISO-8859-15');
$login = new Login($email, $password);
unset($login);
}
check for valid $_SESSION vars
session_start();
if (!isset($_SESSION['id']) || !isset($_SESSION['name']) || !isset($_SESSION['email'])) {
header('Location: index.php');
}
login query (just incase it is needed)
class Login extends Connection {
public function __construct($email, $password) {
$this->connect();
$sql = "SELECT `id`, `name`, `email`, `password` FROM `users` WHERE `email`=:email";
$query = $this->connect()->prepare($sql);
$result = $query->execute(
[
':email' => htmlentities($email, ENT_QUOTES, 'ISO-8859-15'),
]
);
// check if EMAIL exists
if ($result) {
$row = $query->fetch(PDO::FETCH_OBJ);
$id = htmlentities($row->id, ENT_QUOTES, 'ISO-8859-15');
$name = htmlentities($row->name, ENT_QUOTES, 'ISO-8859-15');
$email = htmlentities($row->email, ENT_QUOTES, 'ISO-8859-15');
$hashed_password = htmlentities($row->password, ENT_QUOTES, 'ISO-8859-15');
// check if user input PASSWORD matches the unhashed PASSWORD in the database
if (password_verify($password, $hashed_password)) {
$_SESSION['id'] = htmlentities($id, ENT_QUOTES, 'ISO-8859-15');
$_SESSION['name'] = htmlentities($name, ENT_QUOTES, 'ISO-8859-15');
$_SESSION['email'] = htmlentities($email, ENT_QUOTES, 'ISO-8859-15');
header('Location: blog_roll.php');
} else {
header('Location: index.php');
}
} else {
echo 'THAT EMAIL ADDRESS DOES NOT EXIST';
}
}
}
You have to set the content type for your ajax request
this.xhr.open('POST', '//localhost/mouthblog/', true);
this.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.xhr.send(formData);

alert not popping up in php

In a particular php file iam using a header and an alert box before it executes header, but its neglecting alert and executing header directly..!!please help me resolving this...!!pardon if i went wrong somewere.
.php
<?php
header('location: formprofile.php');
session_start();
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['salutation']) && !empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['dob']) && !empty($_POST['mobile']) && !empty($_POST['country']) && !empty($_POST['state']) && !empty($_POST['city']) && !empty($_POST['pin'])){
/*
if required include seperate validation
for some fields which require validation
*/
// receiving the post params
$salutation = ($_POST['salutation']);
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$dob = trim($_POST['dob']);
$mobile = trim($_POST['mobile']);
$country = trim($_POST['country']);
$state = trim($_POST['state']);
$city = trim($_POST['city']);
$pin = trim($_POST['pin']);
/*
validation process
starts from here
*/
// validate your email address
if(strlen($mobile) == 10){
if($db->isMobileNumberExisted($mobile)) {
//user already existed
$response["error"] = true;
$response["error_msg"] = "user already existed with" . $mobile;
echo json_encode($response);
}else{
// create a new user
$user = $db->storeUser($salutation, $fname, $lname, $dob, $mobile, $country, $state, $city, $pin);
if ($user) {
// user stored successfully
$response["error"] = false;
$_SESSION['fullname'] = $user['fullname'];
$_SESSION['vault_no'] = $user['vault_no'];
$message = "Registration successful";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
}else{
//invalid mobile number
$response["error"] = true;
$response["error_msg"] = "PLEASE ENTER VALID MOBILE NUMBER!";
echo json_encode($response);
}
}else{
//missing the required fields
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
header('location: formprofile.php');
This line is redirecting the page to formprofile.php and that causes to ignore everything below it. Just remove that line or if you want redirect after execution, then move it to the end of the file and do not echo or print anything before it.
But if you want to have some alert before redirecting to other page don't use header() for redirect. Add this JavaScript at the end of the file.
?>
<script>
alert("your message");
document.location = "formprofile.php";
</script>

php login form pass vars

i have a page login
in page have html form with textboxes and submit button
and in top of page i have PHP code thet chacke if name and password in database
if name and password in database page go to new page and pass the name and password to next page
i can do it with get metod like the vars in the URL
but i want to pass and go to new page with Post metod
how i can do it??
pleas help me with code....
in code html :
form name="frmlogin"action="<?= $_SERVER['PHP_SELF'] ?>" method="post" >
and in top of the page have PHP code:
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
/*header('Location: YOUR_LOCATION');
exit;*/
$msg = "Username and password match";
echo '<script type="text/javascript">
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
help me to change the javascript window.location to post metod
You can go for php redirect also.
header('location:smartphon100.php?name='. $name .'&password='. $password) ;
BTW: you are passing password in browser?
If I understand correctly, you're trying to redirect a user after successfully logging in.
I see that your current code attempts to redirect using Javascript, the issue seems to be with the quotes on the value you tried to enter.
Try to change this line:
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
to this:
window.location.href = "smartphon100.php?name='.$name.'&password='. $password";
Overall you should read about security as the code you presented is very vulnerable.
PHP: SQL Injection - Manual
If you're trying to pass the values to another page in a POST method using Javascript, you could take a look at this answer:
JavaScript post request like a form submit
Although as I don't see a reason for posting the values more than once,
I recommend you to read about PHP sessions, cookies, and encryption, which allow you to store values that you can use across the website securely.
A simple example to using session:
<?php
//Starts the session, you need to use this line in every PHP file that'll need to access session variables
session_start();
$_SESSION['user'] = "Donny"; //Storing a user name
?>
A simple example of session use with your code:
Foo.php
session_start();
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['user'] = $name;
$_SESSION['pass'] = $password;
$msg = "Username and password match";
echo '<script type="text/javascript">window.location.href = "smartphon100.php";</script>';
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
Bar.php
<?php
session_start();
//Accessing the values:
echo $_SESSION['user'];
echo $_SESSION['pass'];
?>
NOTE:
It's not good to store values like that as again, they're not secure, please read about hashing passwords.
PHP: Password Hashing

PHP AJAX always returning the same result

So I'm trying to check if the email is already in use (for a password reset). So I have my JS
//Check if email exists
$(document).ready(function() {
//listens for typing on the desired field
$("#email").keyup(function() {
//gets the value of the field
var email = $("#email").val();
//here is where you send the desired data to the PHP file using ajax
$.post("../classes/check.php", {email:email},
function(result) {
if(result == 1) {
//Email available
console.log("Good");
}
else {
//the email is not available
console.log("Bad");
}
});
});
});
And then my PHP
<?php
//Include DB
include_once '../db.php';
if(isset($_POST['email'])){
//Get data
$email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
}
else{
header('Location: /');
}
//Send requst to DB
$stmt = $con->prepare("SELECT * FROM users WHERE email = :email");
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount() > 0){
//Email found
echo 1;
}
else{
//Email not found
echo 0;
}
So I start off by making sure there's a recording in my DB. Which there is, so I enter it. Now I go over to the console and all I get is Bad, which means that the email is not found, but it's in the database. So I'd assume all it returns is 0. Any ideas? Could it be an error in my code?
The PDO documentation warns that rowCount might not work with all drivers. A more reliable and efficient way to do it is:
$stmt = $con->prepare("SELECT COUNT(*) as count FROM users WHERE email = :email");
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['count'] > 0) {
echo 1;
} else {
echo 0;
}
Another thing to try:
$email = trim($_POST['email']);
because sometimes there's extra whitespace in theinput field.

Categories

Resources