I spent many days to fix this problem and i can't find a solution.
After i login using my ajax form + php backend, the page where user is redirected show the "Missing session" message and if i try dumping $_SESSION it looks like empty. Then, if i go back and i do the same login it will work correctly. This happen in different browser (usually when they have cookie and cache clear) and in different hosting providers.
This is my ajax code:
$(document).ready(function(){
$('#loginbtn').click(function(){
if($('#username').val() == "" || $('#password').val() == ""){
return false;
}
else
{
$.ajax
({
type: 'POST',
url: 'ajax_login.php',
cache: false,
dataType: 'json',
data:
{
username: $('#username').val(),
password: $('#password').val()
},
success:function(data)
{
if(data.error === true){
alert("Failed to login: "+data.message)
}
else
{
setTimeout(function()
{
window.location = 'http://www.mywebsite.com/dashboard.php';
},2000);
}
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("An error occured!");
}
});
return false;
}
});
});
This is the PHP Login Backend:
<?php
include "config.php"; // start session and connect to mysql db, also contain functions sanitize(), getip()
$username = sanitize(htmlspecialchars($_POST['username'],ENT_QUOTES));
$pass = sanitize($_POST['password']);
// FUNCTION TO LOGIN
$sql = mysql_query("SELECT * FROM members WHERE username = '$username' AND password = '$pass'");
$array = mysql_fetch_array($sql);
if(mysql_num_rows($sql) === 0){
$message['error'] = true;
$message['message'] = "Wrong username or password.";
echo json_encode($message);
exit;
}
$_SESSION['username'] = ucwords(strtolower($username));
$_SESSION['points'] = $array['points'];
$_SESSION['ip'] = getip();
$_SESSION['welcome'] = true;
$message['error'] = false;
$message['message'] = "Completato.";
echo json_encode($message);
exit;
And finally this is dashboard.php check session code:
<?php
include "config.php";
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
if($_SESSION['username'] == "") {
header("Location: index.php?nosession");
exit;
}
Edit: This is what's inside config.php
<?
session_start();
date_default_timezone_set("Europe/Rome");
$hostname = ""; //hostname
$data_username = "dbxxxxxxxx"; //database username
$data_password = "xxxxx"; //database password
$data_basename = "dbxxxxxxx"; //database name
$conn = mysql_connect("".$hostname."","".$data_username."","".$data_password."");
mysql_select_db("".$data_basename."") or die(mysql_error());
function sanitize($text) { // funzione che pulisce le stringe per prevenire exploit;
if(get_magic_quotes_gpc() == 0) {
$text = addslashes($text);
}
$text = htmlentities($text);
$text = strip_tags($text);
$escape = mysql_real_escape_string($text);
$arraydangerous = array('SELECT *', 'LOAD_FILE', 'DELETE', 'TRUNCATE', '\' OR', '<javascript>', 'src=', '<?', '?>', 'document.cookie', 'http://', 'www.');
$text = str_replace($arraydangerous, "", $text);
return $text;
}
function getip()
{
return filtra($_SERVER['HTTP_CF_CONNECTING_IP']); // I use CloudFlare ,so i must use this way :)
}
How can i fix this? Thanks
In config.php add this lines after session_start();.
session_start();
// reset the session, if not logged-in
if (empty($_SESSION['username'])) {
$_SESSION['username'] = null;
$_SESSION['points'] = null;
$_SESSION['ip'] = null;
$_SESSION['welcome'] = null;
}
Also I guess it's better you changing dashboard.php to something like this:
<?php
include "config.php";
if($_SESSION['username'] == "") {
header("Location: index.php?nosession");
exit;
}
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
?>
I think your problem is the old sessions that you have on your server, while testing your code. For example you are trying to log in, you add the values to the session but for any reason you receiving some errors, and you see that you're not logged in. You forgot that you already add some data to the session, you refresh the dashboard.php and you see that hey, it seems that you're already logged in. Then you might think that your code is crazy, working randomly or any other irrelevant reason. (a few years ago, I had a code that was working when it was raining on the day, and didn't work when it wasn't rainy. Fortunately, I solved that problem in 2 days, before getting crazy!)
You might also clean all the sessions stored on your server, to be sure you have a clean test, while you're changing the code.
I hope these gonna helps somehow.
I'm not sure if this is the case or what (since I don't know what's inside config.php), but it seems to me that you forgot to start the session before you use it in your "PHP Login Backend" file!
Related
$_SESSION['isloggedin'] doesn't seem to be working on first load.
This only happens on server, not on localhost.
session_start() is at the top of each page.
initialized to: $_SESSION['isloggedin'] = false;
When user logs in $_SESSION['isloggedin'] = true;
When user logs out $_SESSION['isloggedin'] = false;
on home.php:
if (!$_SESSION['isloggedin']) {
die(header("Location: login.php"));
}
on login.php:
if ($_SESSION['isloggedin']) {
die(header("Location: home.php"));
}
When you login and sent to the home page $_SESSION['isloggedin'] doesn't seem to be true so it redirects to login.php. But since it is true it redirects to Home.php causing a redirect loop.
when a redirect loop error pops up, I refresh and am taken to the right page. Sometimes the page self refreshes and takes me to the correct page, still showing redirect error before.
Why isn't $_SESSION variable working properly on server? The correct value doesn't seem to register the first time on every page, every site link.
EDIT:
everything works as expected on localhost just not on the online server.
when login is clicked and everything passes the class login function is called:
class users {
$_SESSION['isLoggedIn'] = false;
function __construct() {
if (session_id() == "") {
session_start();
}
if (isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] == true) {
if (session_id() == '') {
session_start();
}
}
}
function login($user,$password) {
if (session_id() == "") {
session_start();
}
$_SESSION['isLoggedIn'] = false;
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if ($mysqli->connect_errno) {
return false;
}
$user = $mysqli->real_escape_string($user);
$password = $mysqli->real_escape_string($password);
$query = "SELECT * from users WHERE email=$user";
if (!$result = $mysqli->query($query)) {
return false;
}
$row = $result->fetch_assoc();
$db_pass = $row['password'];
if (crypt($password,$db_pass) != $db_pass) {
return false;
}
$_SESSION['isLoggedIn'] = true;
if (session_id() == '') {
session_start();
}
return true;
}
}
Try changing your code to something like this
if (!isset($_SESSION['isloggedin'])) {
header("Location: login.php");
} else {
header("Location: home.php");
}
I was using AWS Elastic Beanstalk to run this web app. I didn't think this matter but apparently it did. It turns out that sessions don't work the same as they do on localhost since you are dividing your servers. I needed to enable sticky session within the load balancer.
I am having problems with my code. This is a login/register script I've made by following a tutorial.
The problem I have is that I want the script to echo "logged in" ONLY when the user has entered correct login details, and yet it still echoes "logged in" even if I don't enter any login details. I checked it and if I delete the "session_start()" function, it doesn't do the same thing, but it still doesn't give me access to the session when I want to login.
This is the init.php file, used to initiate the connection with the database and define some other functions:
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
?>
This is the connect.php file, used to connect to the database :
<?php
$connect_error = 'Sorry, we are experiencing connection issues. This will be solved as soon as possible.';
$con=mysqli_connect("localhost","root","","lr") or die ($connect_error);
mysqli_select_db($con,'lr') or die($connect_error);
mysqli_close($con);
?>
The general.php file is not important for this question.
This is the users.php file, where I keep some other functions.
function user_id_from_username ($username){
$username = sanitise($username);
$mysqli = new mysqli("localhost", "root", "", "lr");
$query = "SELECT * FROM users";
$result = $mysqli->query($query);
while($row=$result->fetch_row()){
if ($row[1]==$username){ //username == $username
return $row[0];//user_id;
}
}
}
function login ($username, $password){
$user_id= user_id_from_username($username);
$mysqli = new mysqli("localhost", "root", "", "lr");
$username = sanitise($username);
$password =md5 ($password);
$query = "SELECT * FROM users";
$result = $mysqli -> query($query);
while ($row =$result -> fetch_row()){
if($row[1]==$username && $row[2]==$password){
return TRUE;
}else {
return FALSE;
}
}
}
This is the file that calls the login function, presented above:
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) ===TRUE || empty ($password) === TRUE) {
$errors[]='You need to enter a username and password!';
} else if (user_exists($username) ===FALSE) {
$errors[]="We can't find that username, have you registered?";
} else if (user_active($username)===FALSE){
$errors[]="You have not activated your account!";
} else{
$login = login($username, $password);
session_start();
if ($login ==false) {
$errors[] ='That username/password combination is incorrect!';
}else if ($login==true) {
//set the user session
$_SESSION['username'] = $login;
//redirect user to homepage
header('Location: index.php');
exit();
}
}
if ($errors){
print_r($errors);
}
}
?>
And now the index.php file, in which I have the if statement that echoes 'logged in' even if I am not logged in :
<?php
if (empty($_SESSION['username'])) {
echo 'not logged_in';
}else {
echo 'logged in';
}
?>
Now I think the problem is located somewhere either in the users.php, login.php or in the index.php file. I presented all of the files so you could get an idea of what I am trying to achieve. This code is spread over so many files because I have functions and interfaces that I have included and I want to be able to reuse the code, so I am using includes.
For you to get a better idea, if my files did not help you enough, I will leave the Youtube link of the tutorial I am following :
https://www.youtube.com/watch?v=JUk2e8oqOvI&list=PLE134D877783367C7&index=7#t=6.296979
Thank you,
Waiting for your answer,
Best regards,
If you don't use $_GET requests to include the pages, you need to put session_start() on top of each file where you are using the $_SESSION variable otherwise you can't use the sessions.
<?php
session_start();
// Rest of your script
I hope this will help you.
I have a class named User which has a function named logout(). I create an instance of this class in index.php and i pass it's value to $_SESSION[usr] before i call memberspage.php . In memberspage.php i have a link named logout which when clicked i want the logout() function to run and also send the user to index.php. For this purpose i've done something like this.
Log out
I know that -> causes the problem but i don't know how to fix it. thnx for your time.
The following code worked for me
Log out
but there is a problem. If i go to the page(memberspage.php) where the above code is and i press the back arrow (not logout link) the logOut() function will still be used(the session is destroyed and i will have to log in again to access memberpage.php) . I don't get it because i thought that the only way to call the logOut() function was to click on Log out link.
If $_SESSION[usr]->logout() is working for you as you said in your comment. I don't know how.
But here is just for calling a php function inside anchor tag.It's totally depend on your function response.
<?php
function usr(){
return "abc";
}
?>
Log out
First i suggest that you change your use of session you can create a page for example session.php where all your session is place, it can also be the re directory page of your login page.
like this one named login.php
create in your form make action redirect to session.php
i also suggest that all your php codes of login are inside the session.php then make this one.
<?php
session_start();
$host = "localhost";
$uname = "root";
$pass = "";
$db = "mydb;
//database connection
$conn = mysqli_connect($host, $uname, $pass, $db);
mysqli_select_db($conn, $db);
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
//$username = mysqli_real_escape_string($username);
//$password = mysqli_real_escape_string($password);
$sql = "SELECT * FROM table WHERE username = '" .$username. "' AND password = '".$password."' LIMIT 1";
$res = mysqli_query($conn, $sql);
if(mysqli_num_rows($res) > 0){
if($data = mysqli_fetch_assoc($res))
{
$_SESSION['type'] = $data['type'];
if(isset($_SESSION["login_user"]))
{
if($data['type'] == 'admin'){
header('location: admin.php');
}
else if($data['type'] == 'customer'){
header('location: customerhome.php');
}//header('location: uservalidation.php');
}
}
}
else{
//header('location: #');
echo '<script>';
echo 'alert("Invalid no?")';
echo '</script>';
header('location: logind.php');
}
}
?>
then create another page which is logout.php
put this code inside:
<?php
session_start();
header('location: index.php');
session_destroy();
?>
then save put the a link your page for logout.php
Add file logout.php and put into them your logout implementation:
<?php
header('Content-Type: application/json');
$_SESSION[usr]->logout();
echo json_encode(['message' => 'ok']);
And call this file with AJAX:
<script>
function logout() {
$.ajax({
url: '/logout.php'
}).then(function (res) {
window.location.href = '/';
});
}
</script>
Log out
I don't know how to get to the main page index.php and show some div's with javascript function after i check if the login data is correct. I run login.php scrip after the user clicks on submit button, and than if user data is correct i want to show some div's with javascript and stay on index.php page. I tried this using javascript function and than the header(location: ./index.php) in php but it didn't work.
My code:
if($name == $username && $pass == $password){
echo '<script type="text/javascript">'
, 'showDiv();'
, '</script>';
header("Location: ./index.php");
}
Put session_start(); at the top of your login.php and index.php files, then put this in your login.php file:
if ($name == $username && $pass == $password) {
$_SESSION['authenticated'] = true;
header("Location: ./index.php");
}
Then, on your index.php file, do this to see if the user is logged in:
if (isset($_SESSION['authenticated']) && $_SESSION['authenticated']) {
echo '<script type="text/javascript">'
. 'showDiv();'
. '</script>'; # If you want your div to show on your index.php
}
The way you are using seems weird. A better approach would be to use SESSION variables to store login info(when user logs in) and display content after checking the SESSION variable like this:-
if(isset($_SESSION['somevalue']))
{
echo 'whatever you want';
}
if($name == $username && $pass == $password)
$_SESSION['login'] = true;
Now anyhwhere in code first start session and check for login name session variable.
session_start();
if (isset($_SESSION['login'] ) && $_SESSION['login'] === true)
{
//do what logged in user require
}
else
{
// redirect them to login page with proper error.
}
In your login.php write this.
session_start();
if($name == $username && $pass == $password){
$_SESSION['somevalue'] = $username;
header("Location: ./index.php");
}
In index.php You need to check whether your session is set or not? If set show youw div with javascript code.
session_start();
if(isset($_SESSION['somevalue']))
{
//show your div code here.
}
You have to write session_start(); in first line of your login.php file. Because some time it has problem.
session_start(); // line 1 in login.php
if($name == $username && $pass == $password)
{
$_SESSION['mydata'] = $username;
header("Location: ./index.php");
}
Actually you need to use some Jquery and an Ajax call in order to not refresh the page once the user clicked the submit button.
The code you need is something like this:
$.ajax({
'url': 'http://yourdomain.com/authentication_script.php',
'beforeSend': function(xhr) {
xhr.setRequestHeader("Authentication", "Basic " + encodeBase64(username + ":" + password)
},
sucess: function(result) {
alert('authenticated'); // here you can add some other functions to execute once authenticated
}
});
The idea is that you should take care that in the authentication script you should also include session variables and keep track of the user data as long as you / he want/s.
We have a login form that is processed by php and ajax. The ajax sends a request to the php page with the username and password to be logged in. It gets a response and if it's correct and working info, it logs them in:
The php page that takes requests has this code:
echo (checkLogin($_POST['user'], $_POST['pass']) ? 'true' : 'false');
if(checkLogin($_POST['user'], $_POST['pass']) == true)
logIn($_POST['user'], $_POST['pass']);
The functions used in that statement:
function logIn($user, $pass)
{
$_SESSION['sid'] = md5(md5($user) . md5($pass));
$_SESSION['username'] = $user;
$_SESSION['password'] = $pass;
}
function checkLogin($user, $pass)
{
$user = strtolower($user);
$pass = strtolower($pass);
$res = mysql_query("SELECT * FROM users WHERE username='".$user."'");
if(mysql_num_rows($res) == 1)
{
$data = mysql_fetch_assoc($res);
if($data['pass'] == aCrypt($pass))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Now, it seems that the session is started and only able to be seen AFTER the user reloads the page. We need it to start the session right on the page...would we need to refresh the entire page with ajax? I don't really know where to go from here.
You probably want to use the Post-Redirect-Get pattern; after the user is successfully authenticated, use a redirect to send him to a new page.
As I noted above, please look into fixing the SQL injection and session fixation vulnerabilities in your code as well.