undefined index for cookie in some browsers - php

I am using a log in script that I found on experts exchange to make a cookie when a user logs on.
The login page processes like this:
function process_login() {
var username = $.trim($('#input_username').val());
var password = $.trim($('#input_password').val());
username = $.trim(username);
password = $.trim(password);
var remember = document.getElementById("remember_user_checkbox").checked;
if (!username || !password) {
return false;
}
remember == true ? remember = "true" : remember = "false";
$.ajax({
type: "POST",
cache: false,
url: "login_user.php",
data: "username=" + username + "&password=" + password + "&remember=" + remember,
dataType: "json",
success: function (data) {
if (data == "FALSE") {
$('#input_password').val("");
alert("The username or password you have entered is incorrect.");
return false;
}
window.location = "orders-home.php?<?=time()?>";
}
});
}
And submits to login-user.php, here:
<?php
include('login-config.php');
$username = pg_escape_string($_POST['username']);
$password = pg_escape_string($_POST['password']);
//no encryption for now
//php gets this as a string
$remember = $_POST['remember'];
if ( $remember == "true" )
{
$remember = TRUE;
}
else
{
$remember = FALSE;
}
$user_query = "SELECT * FROM users WHERE username = '$username' AND password = '$password' LIMIT 1";
$user_result = pg_query( $con , $user_query );
if ( !$user_result )
{
echo json_encode("FALSE");
}
$arr = array();
if (!$user_result)
{
die( pg_last_error($con) );
}
else
{
while ( $row = pg_fetch_array($user_result) )
{
//put the customer id in a session so we can put it in a cookie later
//then when the page is refreshed the stored customer id will be used
//as their ksisoldby identifier
if ( $row['cust_id'] )
{
$_SESSION['customer_id'] = $row['cust_id'];
$_SESSION['customer_name'] = $row['first_name']." ".$row['last_name'];
$_SESSION['uid'] = $row['id'];
if ( $remember )
{
remember_user($row["id"]);
}
}
$arr[] = array(
"first_name" =>$row['first_name'],
"last_name" =>$row['last_name'],
"customer_id" =>$row['cust_id'],
"accepted_terms" =>$row['accepted_terms'],
);
}
}
if ( empty($arr) ){
echo json_encode('FALSE');
}
else
{
$path = '/webtrack';
$site = 'www.isco.net';
if ($remember === TRUE)
{
$remember_time = time()+60*60*24*30;
setcookie('username', $username, $remember_time, $path, $site);
setcookie('customer_id', $_SESSION['customer_id'], $remember_time, $path, $site);
setcookie('customer_name', $_SESSION['customer_name'], $remember_time, $path, $site);
// setcookie('uuk', $uuk, $remember_time, $path, $site);
}
else
{
setcookie('username', $username, false, $path, $site);
setcookie('customer_id', $_SESSION['customer_id'], false, $path, $site);
setcookie('customer_name', $_SESSION['customer_name'], false, $path, $site);
}
echo json_encode($arr);
}
?>
I then print from that cookie onto the main screen
<div class="fl customer_id">
<?= strtoupper($_COOKIE['customer_name']); ?>
</div>
But I getting the error
Notice: Undefined index: customer_name in /home/iscotest/public_html/webtrack/orders-home.php
The actual site is www.isco.net. But the website is hosted at iscotest.com. isco.net simply points to iscotest.com. Could this be why my cookie isn't being set?
It is quite a problem because this totally ceases the load of the page, as that cookie information is used to retrieve the data that is displayed
The other odd thing is that this error isn't appearing consistently. I get the error on safari and chrome on one computer, but the site functions normally on another computer in safari and chrome.
Thanks for any help

When you use setcookie () to create a COOKIE this will only be available on another page. Therefore, it can be a problem with your AJAX.

Related

Why do I get the empty $_SESSION variable?

It turns out that when I get the variable $_SESSION it's empty, and I do not understand why. Months ago it worked perfectly but then one day it no longer recognized the sessions and returns them null, when I call var_dump().
I added session_start() at the beginning of everything, and I receive the $_POST parameters correctly, but when I save the session variable on another page it is lost and null arrives.
What can be the causes of this occurring, if before it worked well? I regret if the question is not the right one, I would like to know the causes of why now they are not received and before if, it is possible to clarify that I am in a hosting.
<?php
session_start();
include "db.php";
$stmr = $con->prepare("SELECT * FROM USUARIOS WHERE NOMBRE = ? AND PASSWORD = ? ");
$usuario = $_POST["usuario"] ?: "";
$password = $_POST["password"] ?: "";
$stmr->bind_param("ss", $usuario, $password);
$stmr->execute();
$resultadoCons = $stmr->get_result();
if ($resultadoCons->num_rows > 0) {
while ($row = $resultadoCons->fetch_assoc()) {
if ($row["ID_TIPO"] == 1) {
$_SESSION["administrador"] = $usuario;
echo "administrador";
} else if ($row["ID_TIPO"] == 3) {
$_SESSION["admin"] = $usuario;
echo "admin";
} else {
$_SESSION["usuario"] = $usuario;
echo "usuario";
}
}
} else {
echo "error";
}
$con->close();
This is the validate. I'm using AJAX
/* Login */
$(document).ready(function() {
$('#formulario').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'config/validate.php',
data: $(this).serialize(),
success: function(response)
{
// var jsonData = JSON.parse(response);
if (response == "administrador")
{
location.href = 'admin.php';
}else if(response == "usuario"){
location.href = 'homeUsu.php';
}else if(response == "admin"){
location.href = 'home.php';
}
else
{
Swal.fire({
icon: 'error',
title: 'Oops...',
text: '¡Sus credenciales son incorrectas,reintente!',
})
}
}
});
});
});
If you need more code, or context I will be attentive, thank you very much!
First Check If You Have A Cookie Named: PHPSESSID or not in your browser.
Also It Can be that The Directory Where Your Sessions Are To Be Stored Is Not Writeable And You Don't Have Sufficient Permissions. In Most Cases, It's The /tmp directory.
You Can Use the following code to determine if your sessions dir is writeable or not:
$session_dir = session_save_path();
if (is_writable($session_dir)) {
echo 'It Is Writeable';
} else {
echo 'Not Writeable!';
}
If you get Non Writeable, then go ahead and make the directory writeable or change the session save dir using the following code:
ini_set('session.save_path', '/path/to/your/writeable/folder')

Unable to verify password using password_verify

WHen user clicks submit button, ajax will pass data to a php scripts to check if login valid or invalid.
Below, password is not verified. The data passed(email,password) to the checkLogin class are correct, because other data can be retreived using the email address.It's only when it comes to
$flag=false;
if (password_verify($this->password, $hashAndSalt)) {
$flag=true;
}
its returning false. I couldn't spot the mistake.Can anyone see what is wrong in my script?
js
/*login user*/
$("document").ready(function(){
$("#login-user").submit(function(){
alert("submited");
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "text",
url: "login-this-user.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
alert(data);
}
});//end success
return false;
});//end form
});
PHP
<?php
session_start();
include('config.php');
include('class.login.php');
//$return = $_POST;
$return ='{"email":"jane#ymail.com","pass":"jane","action":"test"}';
//$return['json']= json_encode($return);
//
//below code to store in database
$data = json_decode($return, true);
$login = new checkLogin();
$return_value = $login->checkLogin($data["email"],$data["pass"]);
echo $return_value;
?>
class to check login
<?php
class checkLogin
{
public $email;
public $password;
public $userId;
public $salt;
public $hpass;
public function __construct()
{
}
public function checkLogin($param1, $param2)
{
$this->email=$param1;
$this->password=$param2;
$sql = "SELECT *FROM agency WHERE agency_email='{$this->email}'";
$statement = connection::$pdo->prepare($sql);
$statement->execute();
while( $row = $statement->fetch()) {
echo "salt ".$salt=$row['agency_salt'];
echo "hash ".$hashAndSalt=$row['agency_pass'];
$user_id=$row['agency_id'];
}
$flag=false;
if (password_verify($this->password, $hashAndSalt)) {
$flag=true;
}
return $flag;
}
}
?>
Table structure
Hashing when signing up user and storing password:
/*....salting starts........*/
$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
//$salt = sprintf("$2a$%02d$", $cost) . $salt;
$options = array('cost' => $cost,'salt' => $salt);
//$password = crypt($data['password'], $salt);
$hash = password_hash($data['passsword'], PASSWORD_DEFAULT,$options);
/*..........salting ends..............*/

$_SESSION variable not setting in AJAX call

I wrote this call for user authentication:
$( '.sign-in' ).click( function(e) {
e.preventDefault();
var logincall = $.ajax({
type: "POST",
url: "../snippets/auth.php",
data: { username: $('#id_email').val(), password: $('#id_password').val() }
});
logincall.done(function( result ) {
alert( 'finished: ' + result );
if( result == 'valid' ) {
location.reload();
} else {
$( '.warning' ).toggleClass('hidden');
}
});
logincall.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
and here's the auth.php function
if( isset($_POST['username']) && isset($_POST['password']) ) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$query = "SELECT COUNT(*) FROM member WHERE username='$username' AND password='$password';";
$result = $mysqli->query($query);
$result = $result->fetch_array(MYSQLI_ASSOC);
if( $result['COUNT(*)'] !== 0 ) {
$_SESSION['logged'] = true; //this sets
$query = "SELECT id, level FROM member WHERE username='$username' AND password='$password';";
$result = $mysqli->query($query);
$result = $result->fetch_array(MYSQLI_ASSOC);
$_SESSION['uid'] = $result['id']; //this DOES NOT set
$_SESSION['lvl'] = $result['level']; //this DOES NOT set
echo json_encode('valid');
} else {
echo json_encode('invalid');
}
}
The odd thing is, if I navigate directly to
myurl.com/snippets/auth.php?username=myusername&password=mypassword
it DOES set the other two session variables, but I can never get index.php to pick them up.
I even added that refresh line to it to ensure it could pick them up, and it gets $_SESSION['logged'] just fine, but not ['uid'] or ['level']

Checking if username exists in Database jQuery

I want to check if the username is already taken, here is my script, which outputs "undefined". Can anyone help me, please? :)
This is in my jQuery - $("#registerusername").val() is the value of an input.
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data.exists);
if(data.exists){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
}, 'JSON');
This is in my checkregister.php
header('content-type: text/json');
if(!isset($_POST['username']))
exit;
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
echo json_encode(array('exists' => $query->rowCount() > 0));
First, You might want to strengthen your php against sql injection by 'sanitizing' the input.
Next why return JSON from the php? It would be much simpler to just return either true or false.
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
if( $query->rowCount() > 0 ){
echo 'true';
}
else{
echo 'false';
}
Then in your javascript:
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data);
if(data == 'true'){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
});
edit---
You could also just return a boolean variable from php rather than a string, but either will work
Simple Example..
Jquery
var username = $.trim($('#username').val());
if(username != '') {
$.ajax({
url : 'localhost/phpScript.php',
data : {username : username},
dataType : 'JSON',
type : 'POST',
cache : false,
success : function(result) {
if(result == '1') { alert('Username Found.'); }
else if(result == '0') { alert('Username Not Found!'); }
},
error : function(err) {
console.log(err);
}
});
}
PHP/MySQL (Make sure that you escape value for user input, Before giving it to MySql)
if(isset($_POST['username'])) {
$username = $_POST['username'];
$sql = "SELECT username FROM users WHERE username = '".$username."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == '1') {
echo '1';
} else {
echo '0';
}
}

passing and acting upon multiple json encoded strings

function logsig() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = '&username=' + username + '&password=' + password;
if(username=='' || password=='') {
$('#success').fadeOut(400).hide();
$('#error').fadeOut(400).show();
} else {
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?=base_url()?>index.php/home/logsig",
data: dataString,
json: {session_state: true},
success: function(data) {
if(data.session_state == true) {
window.location = "<?=base_url()?>";
} else if(data.session_state == false) {
$("#login_failure").fadeIn(400);
}
}
});
}
}
How can I pass multiple json encoded values to my form above. What I'm doing is if user logs in, 'session_state' is passed, and if user has a 'pending' account, 'pending' is passed. Both json values have an expression to be executed.
public function logsig() {
header('Content-type:application/json');
$postedEmail = $this->input->post('username');
$password = $this->input->post('password');
$hashedPass = $this->encrypt->sha1($password);
$query = $this->db->query("SELECT * FROM users WHERE username = '{$postedEmail}' AND password = '{$password}'");
if ($query->num_rows() > 0) { // if user is already registered and is logging in, execute the following sql/php commands.
$row = $query->row();
if ($row->status == "pending") {
echo json_encode(array('pending' => true));
} else {
echo json_encode(array('pending' => false));
}
//$this->session->set_userdata('userid', $idgen);
//$this->session->set_userdata('email', $postedEmail);
$this->session->set_userdata('logged', "1"); // 1 means user is logged in.
echo json_encode(array('session_state' => true));
} else {
echo json_encode(array('session_state' => false)); // false sends to jquery that member isn't registered
}
}
You should collect all your data and at the end output it as the single JSON string. For example:
$output= array();
if ($query->num_rows() > 0) {
$row = $query->row();
// Status flag
$output['pending'] = $row->status == "pending";
$this->session->set_userdata('logged', "1"); // 1 means user is logged in.
// Session state
$output['session_state'] = true;
}
else {
$output['session_state'] = false;
}
header('Content-type: application/json');
die(json_encode($output));
Or in this case even better (optimized true-branch):
$row = $query->row();
$this->session->set_userdata('logged', "1"); // 1 means user is logged in.
// Session state
$output = array(
'pending' = $row->status == "pending",
'session_state' = false
);

Categories