Why do I get the empty $_SESSION variable? - php

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')

Related

Not redirecting to another page after successful ajax request complete

I am validating a sign In form through ajax. After successful validation the form is not redirecting to the required page.
Ajax Codes
function login_submit(){
var stat="";
$("#submit").val("Loging in...");
$.ajax({
type: "POST",
url: "php/login.php",
data: {
uname: $("#uname").val(),
pass : $("#pass").val()
},
success: function(result) {
if(result=="parent"){
window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index";
}
else if(result == "sucess_normal"){
window.location.assign("../normal_admin");
}
else if(result == "deactivated account") {
window.location.assign("reactivate_account/");
}
else if(result == "banned account") {
window.location.assign("banned_account/");
}
else{
$("#submit").val("Login");
$("#error_msg").css({color: 'red'});
document.getElementById("error_msg").innerHTML= result;
stat = false;
}
}
});
if(!stat)
return false;
}
The php code
if(isset($_POST['uname']) && isset($_POST['pass'])){
$username = encode($_POST['uname']);
$password = encrypt(encode($_POST['pass']));
// check if entered username and password is in the database
$result = mysqli_query($conn,"SELECT * From admin_account where admin_account.username = '$username' AND admin_account.password = '$password' ");
if($row = mysqli_num_rows($result) == 1){
$found = mysqli_fetch_array($result);
if($found['state'] == 1){
$account_id = $found['account_id'];
setcookie("admin_id", $account_id, time() + (86400 * 30), "/");
$_SESSION['admin_id'] = $account_id;
$result1 = mysqli_query($conn,"SELECT role_id From admin where admin_id = '$account_id'");
$found1 = mysqli_fetch_array($result1);
$_SESSION['account_type'] = $found1['role_id'];
if($found1['role_id'] == "1"){
echo "parent";
//header("Location: http://localhost:90/auction/augeo/admin/parent_admin/index");
}else{
echo "sucess_normal";
}
}
elseif($found['state'] == 2){
echo "banned account";
}
else{
$_SESSION['deactivated_id'] = $found['account_id'];
echo "deactivated account";
}
}
else{
echo "Incorrect Username or Password";
}
}
I have tried all I could do but to no avail. I want to check if result=="parent" and if result=="parent" it should redirect to window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index"; but instead it is echoing out parent.
You say "it is echoing out parent". But this should never happen with the AJAX code you supplied.
So I'm suspecting that you have a form that's running its own default submit, and that is what you're seeing.
You may want to check out this answer:
$('#idOfYourForm').submit(function() {
var $theForm = $(this);
// This is a button or field, right? NOT the form.
$("#submit").val("Logging in...");
$.post(
'php/login.php',
{
uname: $("#uname").val(),
pass : $("#pass").val()
}
).done(function(result) {
// check the result
alert("Server said: " + result);
});
// prevent submitting again
return false;
});
You get the button with
$("#submit")
This is ok, but if the button is defined as:
<input type="submit" id="submit" value="..." />
You'll get a subsequent submit of the form the button is defined in.
To avoid this, a far easier solution to the other suggested, is to not use a submit button at all. Instead, use a simple action button. These are two examples, the second of which is probably better because it is easier to design with bootstrap/HTML5/CSS...
<input type="button" id="submit" value="..." />
or better:
<button type="button" id="submit">...</button>
In case of slow server/network, you'll probably want to aid AJAX usability by disabling the button:
$("#submit").val("Logging in...").prop("disable", "disable");
This helps avoiding multiple submits when the server is slow and the user impatient.

Redirect from php file to html

Here my php code. I need to redirect to another page when if($users[$name] === $password) or when $users[$name] = $password; but it does not work.What is wrong?Here ajax too.
$(document).ready(function() {
$('#submit').click(function() {
var name = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'php/login_script.php',
data: {
user: name,
pass: password
},
success: function(a) {
alert(a);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
if(!isset($_POST['user'])||!isset($_POST['pass'])){
die();
}
$file = "users.json";
$users = json_decode(file_get_contents($file), true);
$name = $_POST['user'];
$password = $_POST['pass'];
if(isset($users[$name])) {
if($users[$name] === $password){
header("Location:chat.html");
exit;
}
else {
echo "Wrong password";
}
}
else {
$users[$name] = $password;
file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
header("Location:chat.html");
exit;
}
Because you're fetching the page with ajax the redirection will happen to the ajax request which means you will get back a 301 response.
This should work:
$(document).ready(function() {
$('#submit').click(function() {
var name = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'php/login_script.php',
data: {
user: name,
pass: password
},
success: function(a) {
document.location = 'chat.html';
},
error: function() {
alert('Invalid password');
}
});
});
});
and
<?php
if(!isset($_POST['user'], $_POST['pass']) || empty($_POST['user']) || empty($_POST['pass'])){
// Send bad request so redirect doesn't happen
http_response_code(400);
die();
}
$file = "users.json";
$users = json_decode(file_get_contents($file), true);
$name = $_POST['user'];
$password = $_POST['pass'];
if(isset($users[$name])) {
if($users[$name] != $password){
http_response_code(400);
echo "Wrong password";
}
}
else {
$users[$name] = $password;
file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
}
This will return 200 on success and 400 on failure which will trigger the success and error parts of the $.ajax request.
The thing you need to realize about PHP is all of the PHP stuff is done before sending the page to the user, so calling a redirect on php/login_script.php does nothing.
What you need to do is return something to indicate success of the login.
Here's what you should do to understand my explanation:
Replace header("Location:chat.html"); with echo "success"; in your PHP code.
Change your jQuery to the following:
success: function(a)
{
if (a === "success")
{
window.location.replace("chat.html");
}
}

Javascript, Php, Ajax

I have a problem with this my script.
$("#login").click(function(event) {
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "login.php",
method: "POST",
data: {userLogin:1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "1"){
alert(data);
}
}
})
I want it to alert a value that I am getting from an echo in another php file
<?php
if(isset($_POST['userLogin'])){
$email = mysqli_real_escape_string($con, $_POST['userEmail']);
$password = md5($_POST['userPassword']);
$sql_login = "SELECT * from database where email = '$email' AND password = '$password'";
$query_login = mysqli_query($con, $sql_login);
$count_login = mysqli_num_rows($query_login);
if($count_login == 1){
$row_login = mysqli_fetch_assoc($query_login);
$_SESSION['uid'] = $row_login['user_id'];
$_SESSION['name'] = $row_login['first_name'];
echo "1";
}
}
?>
If I didn't put the alert(data) in an if condition, it displays the value I echo, but I need the condition to enable the right user logged in.
What can IF can also ELSE.
In your ajax add the else conditions to see if it helps uncover the issue:
if (data == "1") {
alert('youre in');
} else {
alert('try again');
}
And in your php, also account for the else condition (and do strict checking on that count of rows with ===):
if ($count_login === 1) {
// code ...
echo '1';
} else {
echo 'Sorry, the login is incorrect';
}
It works fine for me, if i always echo "1", the alert(data) show 1, in an if condition and out, pls, echo something else if isset($_POST['userLogin']) or $count_login == 1 are false, or put an
error : function(data) {
$('body').append("<div>"+data.responseText+"</div>")
}
in your ajax, to debug the prob. Because in your .php file, when you echo nothing, it returns a data in error, not in success, maybe that's your prob.

POST - 500 (internal server error )

In my case I am sending POST request by $.post using JQuery and PHP.
But I am gettinh this error in while posting data.
POST https://xxxxxxxxxxxxx/xxxxxxxxxxx/php/control/LoginControl.php 500 (Internal Server Error)
here is my jquery code :
var url = 'php/control/LoginControl.php';
$.post(url,
{
task : "login_verify",
username:_username ,
password:_user_password,
})
.error(function(er){
console.log(er);
})
.success(
function(data){
if(data == true){
window.location = 'index.php';
}else{
$("#user_password" ).css({border:'1px solid red'});
}
}
);
PHP - LoginControl.php
<?php
try{
if(isset($_POST) && $_POST['task'] == 'login_verify'){
$user_name = $_POST['username'];
$password = md5($_POST['password']);
require '../class/login.php';
if(class_exists('Login')){
$user = Login::verifyCredentials($user_name,$password);
if($user != NULL){
if(isset($_SESSION)){
session_destroy();
}
session_start();
$_SESSION['uid'] = $user[0]->ADMIN_ID;
echo true;
}else{
echo false;
}
}
}
} catch (Exception $ex){
echo $ex;
}
?>
note: I deploy successfully this code on live test server. and it is completely working fine. But on new server I am getting this error. I am using SSL on this new server this might be issue.
Please comment if its not enough information.
Please help.
Here's an edit to your scripts. Maybe something along the lines of this will help.
JS:
$(function()
{
var url = 'php/control/LoginControl.php';
$.post(url, {
task: "login_verify",
username: _username,
password: _password
}, function(data, status, xhr)
{
// success
if(data.error===false)
window.location = 'index.php';
else
$("#user_password").css({border: '1px solid #ff0000'});
}).error(function(xhr, status, error)
{
console.log("Error loading page. Status: "+status+" | Error: "+error);
});
});
PHP:
<?php
// Session must be started before session checking and destroying can happen
session_start();
// Set error true by default
// Error is always returned.
// If no error, it'll be set to false in if statement
// So a value will always be returned.
$return['error'] = true;
if(isset($_POST) && $_POST['task'] == 'login_verify')
{
require_once __DIR__.'/../class.login.php';
if(class_exists('Login'))
{
$uname = $_POST['username'];
$passwd = $_POST['password'];
$user = Login::verifyCredentials($uname, $passwd);
if(!empty($user))
{
if(isset($_SESSION))
session_destroy();
$_SESSION['uid'] = $user[0]->ADMIN_ID;
}
else
$return['error'] = false;
}
}
echo #json_encode($return);
One thing I did notice in your PHP script that I corrected in my edits, is you're using $_SESSION and session_destroy() when no session is open. You must first define session_start() before any of the session methods or magic variables become available to you. That's why I placed it at the very top of the PHP script.
Also, if you want to use another data type rather than json, it's easiest just to use the $.ajax() function
var loginData = {
username: _username,
password: _password,
task: 'login_verify'
};
$.ajax({
url: url,
type: 'post',
data: loginData,
dataType: 'html',
success: function(data, status, xhr)
{
// If page loading was a success. i.e. 200 OK status message
},
error: function(xhr, status, error)
{
// error. Status other than 200
}
});
======================================================================
EDIT: New Code
Take a look at this, see if this will help.
PHP:
<?php
$return['error'] = true;
if(isset($_POST) && $_POST['task'] == 'login_verify')
{
if(!empty($_POST['formData']['username']))
{
if(!empty($_POST['formData']['password']))
{
$return['error'] = false;
$message = "The AJAX call was successfull! The data passed is listed below.\n\n"
. "task: " . $_POST['task'] . "\n"
. "username: " . $_POST['formData']['username'] . "\n"
. "password: " . $_POST['formData']['password'];
$return['message'] = $message;
}
else
$return['message'] = 'Password is empty!';
}
else
$return['message'] = 'Username is empty!';
}
else
{
$return['message'] = 'Invalid request! ' . $json->task;
}
echo #json_encode($return);
JavaScript:
$(function()
{
$("#login").click(function()
{
var jdata = {
task: 'login_verify',
formData: {
username: $("#username").val(),
password: $("#password").val()
}
}
$.ajax({
url: 'login.php',
type: 'post',
dataType: 'json',
data: jdata,
cache: false,
success: function(data, status, xhr)
{
var dataStatus = (data.error===true) ? "Error" : "Success";
var message = "Status: " + dataStatus + "\n"
+ data.message;
alert(message);
},
error: function(xhr, status, error)
{
alert('Error: ' + error);
}
});
return false;
});
});
This code, works. I have a live version of it. Exact code and all.
AJAX/PHP Example
I hope this helps

AJAX username Availability

I have writtin this code to check the email availability.
var email = $('#email_reg').val();
if(email && email.length > 0)
{
if(!isValidEmailAddress(email))
{
isValid = false;
$('#msg_email').html('Email is invalid').show();
}
else
{jQuery.ajax({
type: 'POST',
url: 'check_username.php',
data: 'email='+ email ,
cache: false,
success: function(response){
if(response == 1){
$('#msg_email').html('Email already Exists').show();
isValid=false;
}
else {
$('#msg_email').html('').hide();
}
}
});
}
}
else
{
isValid = false;
$('#msg_email').html('Please enter email').show();
}
The php Code is
<?php
require_once('Connections/connection.php');
$username= mysql_real_escape_string($_REQUEST["email"]);
if (!$con)
{
echo 0;
}
else {
mysql_select_db($database_connection, $connection);
$result = mysql_query("SELECT * FROM vendor_logiin WHERE username='" . $username . "'");
$num = mysql_num_rows($result);
echo $num; //it will always return 1 or 0 since we do not allow multiple users with the same user name.
}
mysql_close();
?>
Now all the others work well like when left it empty and give a wrong email format.But the problem is when i give an email Id that already exists. It didnot give error.
I have no idea what is going wrong.
Since you didn't specify dataType the response is probably treated as text or html and in that case it might be wise to do the comparison as a string:
if (response == "1") {...}
instead of a number. Or use parseInt(response, 10) == 1 if you compare it as a number.

Categories