PHP sessions not being set - php

I have a code which logs in via AJAX and then passes the data to a .php file to check it against the SQL. for a test, the username and password is me - me however even tho this comes back from the check it doesn't log me in, it seems like the session is not being set.
log.php
<script type="text/javascript">
$(document).ready(function()
{
$("#login_form").submit(function()
{
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
//check the username exists or not from ajax
$.post("ejaxlog.php",{ username:$('#username').val(),password:$('#password').val(),rand:Math.random() } ,function(data)
{
if($.trim(data)=='yes') //if correct login detail
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Logging in.....').addClass('messageboxok').fadeTo(900,1,
function()
{
//redirect to secure page
document.location='http://www.google.com';
});
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Your login detail sucks...').addClass('messageboxerror').fadeTo(900,1);
});
}
});
return false; //not to post the form physically
});
//now call the ajax also focus move from
$("#password").blur(function()
{
$("#login_form").trigger('submit');
});
});
</script>
<link type="text/css" href="formboxes.css" rel="stylesheet">
</head>
<body>
<?
echo $_SESSION['u_name'];?>
<form method="post" action="" id="login_form">
<div align="center">
<div >
User Name : <input name="username" type="text" id="username" value="" maxlength="20" />
</div>
<div style="margin-top:5px" >
Password :
<input name="password" type="password" id="password" value="" maxlength="20" />
</div>
<div class="buttondiv">
<input name="Submit" type="submit" id="submit" value="Login" style="margin-left:-10px; height:23px" /> <span id="msgbox" style="display:none"></span>
</div>
</div>
</form>
this then checks the MySQL via the next code, is it is successful it echos out "yes" which i see in my HTTP headers (so must be correct) but it doesnt redirect me to "eindex.php" as specified in the log.php file.
<?php
session_start();
require("../mcfrdb.php");
// Included database once using the require method
?>
<?php
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$pass = mysql_real_escape_string(stripslashes($_POST['password']));
$result = mysql_query("SELECT user, pass FROM mcfruse WHERE user='$username'")or die(mysql_error());
$row=mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
if(strcmp($row['pass'],$pass)==0)
{
echo "yes";
$_SESSION['name']=$username;
}
else
echo "no";
}
else
echo "no";
My HTML when using firebug says
yes
so the yes is being echo'ed which means it passes the right pwd and it validates, but it still says "Login detail sucks" and doesnt redirect me to eindex.php
eindex.php
<?php
session_start();
if(!isset($_SESSION['name']))
header("Location:../index.php");
//if logout then destroy the session and redirect the user
if(isset($_GET['logout']))
{
session_destroy();
header("Location:../index.php");
}
require("../mcfrdb.php");
?>
I've checked the code over a few times but couldnt find anything. All replies and any help appreciated.
Many thanks.
EDIT: even adding in the md5 pwd hashing (omitted from this code) i still get "yes" and when I echo the username and hash, they are bot matching, the session is not being set still however and not redirecting me. on if($.trim(data)=='yes')

Any page you access via AJAX is a separate request and you will need to call session_start() in order for the session super global to be populated.

Your ejaxlog.php returns yes? Are you sure? Try adding alert(data) or console.log(data) to see what does it return. Seems that your script returns not yes or not only yes (may be, some error?). Obviously, you are not redirected because your JavaScript receives not appropriate string, so it does not redirects you.
Again, try logging/alerting the data which is returned by the script. Or install something like FireBug for FireFox to see all the requests done by the JavaScript.

use session_start() at the top of your ejaxlog.php page

Related

PRG pattern technique with input validation

I have implemented the Post/Redirect/Get Pattern to avoid http post requests to be sent to the server each time the web page is reloaded, but i get a problem.
The Welcome message should only be displayed once when the password is set to test. In my case, it is never displayed, unless you comment out the 4th line.
If you remove that line, PRG pattern is not applied, hence form gets resubmitted on each page reload
The code below is a full working code, paste that directly in your code for testing. or here
<?php
$self = htmlspecialchars($_SERVER["PHP_SELF"]);
if(isset($_POST['Code2']) && ( $_POST['Code2'] == "test")) {
header('Location: '.$self, true, 303);exit; //redirection on the same page
?> <span id="welcome-msg"></span> <!-- Display welcome Message -->
<?php } ?>
<form method="post">
Code:<br>
<input type="text" name="Code2"> <input type="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#welcome-msg").html("Welcome").fadeOut(5500);
</script>
Here is a simple PoC that uses PHP sessions instead of cookies. A client session is identified by a cookie but the client has no control over the data the session stores. You could, in theory, put more sensitive data into the "welcome" message this way, although the login method is still very basic and should at least be done over HTTPS.
<?php
// Start PHP session management
session_start();
$self = htmlspecialchars($_SERVER["PHP_SELF"]);
if (isset($_POST['Code2']) && $_POST['Code2'] === "test") {
// Code is correct, flash the welcome message after redirect
$_SESSION["flash_welcome"] = true;
header('Location: '.$self, true, 303);
exit;
} else if (isset($_POST['Code2']) && $_POST['Code2'] !== "test") {
// Code was sent but is incorrect, flash the incorrect message after redirect
$_SESSION["flash_incorrect"] = true;
header('Location: '.$self, true, 303);
exit;
}
if ($_SESSION["flash_welcome"]) {
// Display welcome message
?><span id="welcome-msg">Welcome</span><?php
}
if ($_SESSION["flash_incorrect"]) {
// Display incorrect message
?><span id="incorrect-msg">Incorrect code</span><?php
}
// Clear flash messages
$_SESSION["flash_welcome"] = false;
$_SESSION["flash_incorrect"] = false;
?>
<form method="post">
Code:<br><input type="text" name="Code2">
<input type="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>$("#welcome-msg,#incorrect-msg").fadeOut(5500);</script>
Your <span id="welcome-msg"></span> is located after a redirection and after an exit() inside an if statement
If the condition exists or not, your span will never be displayed.
You need to move it out of the "if", or add it before the redirection and "exit()"
<?php
$self = htmlspecialchars($_SERVER["PHP_SELF"]);
if(isset($_POST['Code2']) && ( $_POST['Code2']== "test")) {
header('Location: '.$self, true, 303);
exit;
} ?>
<span id="welcome-msg"></span>
<form method="post">
Code:<br>
<input type="text" name="Code2"> <input onclick="event.preventDefault()" type="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#welcome-msg").html("Welcome").fadeOut(5500);
</script>
https://www.tehplayground.com/Hf25u68JYljxkjQu

How to prevent user from bypassing php authentication

We call it html1 for simplicity.
When a user goes to html1, there's a login2.php login page to enable access to client.php which is the hidden page.
It then goes to checklogin.php...if the password and user name matches...it then goes to the hidden client.php page...if not..it goes back to homepage.
The user has to login to be able to view the contents of hidden client.php page.
However the user can access client.php by typing in ..../client.php on the address bar...therefore bypassing the auth page and rendering it useless. I can just type servername/client.php...and it still shows me the contents of client.php...but I want client.php...to be private!
How do I prevent this from happening?
thanks.
first login page...
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<table>
<form method="post" action="checklogin2.php">
<div id="name">User Id: <input type="text" name="****"></div>
<div id="password">Password: <input type="password" name="*******"></div>
<div class="button"><input type="submit" value="Login"></div>
</form>
</table>
</body>
</html>
then it goes to....
checklogin2.php
<?php
$*** = $_POST['****'];
$***** = $_POST['***'];
if($uid == '****' and $***** == '*****')
{
session_start();
$_SESSION['sid']=session_id();
header("location:securepage.php");
}
else
{
header("location:index.html");
}
?>
Then it goes to...
securepage.php
<?php
session_start();
if($_SESSION['sid']==session_id())
{
header("location:client.php");
echo "<a href='logout.php'>Logout</a>";
}
else
{
header("location:login.php");
}
?>
In the beginning of your every page you have to check if user is authorized.
On checklogin.php if user entered correct login and password, just set something like
$_SESSION['authorized'] = TRUE;
...and on other pages just check if user is authorized:
if (isset($_SESSION['authorized']) && $_SESSION['authorized'] === TRUE) {
// Alright, let's show all the hidden functionality!
echo "Psst! Hey! Wanna buy some weed?";
} else {
// User is not authorized!
header('Location: login.php');
exit();
}
Note that you don't have to mess with cookies, session IDs etc. - just add session_start() before everything and freely use $_SESSION var.
This is the main pro of sessions (and $_SESSION variable in particular): you can remember some data among different pages on same website.
All pages has to check if the user is authed. I would recommend using objects, and always inherit a class that checks this for you. It's not fun to have the same code everywhere, doing the same thing.
if($_SERVER["PHP_SELF"] == '/yourpagefolder/yourpage.php' && !isset($_SESSION['login_user'])){
header('location: login.php');
}

Session variables not passing to next file

So I've searched this site about this issue and tried what has been suggested and still no luck. I thought maybe it was my 'server' (On my tablet using KSWEB, no computer right now) so I created 2 simple files to share a session variable between the two and it worked fine. I have no idea why this isn't working for these two. I'm trying to create a login page (an insecure one, I know). The error function USED to work (this is what gets me), and now it doesn't. The files are below. I only included the top portion of admin.php because I've commented out the rest. It really shouldn't matter. Right now, if you submit the form without entering anything into the admin prompt, an error should display next to the asterisk saying "Admin needs to be filled out". Despite my best efforts, this doesn't work anymore and I'm completely stumped as to why.
Login.php
<?php
session_start();
?>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<script>
function submitForm()
{
document.adminform.submit();
}
</script>
</head>
<?php echo $_SESSION["adminErr"];?>
<h2>Administrator login page</h2>
<form method="post" action="admin.php" name="adminform">
Admin: <input type="text" name="admin" style="position:absolute; left:100px">
<span class="error" style="position:absolute; left:285px">*<?php echo $_SESSION["adminErr"];?></span>
<br><br>
Password: <input type="password" name="password" style="position:absolute; left:100px">
<span class="error" style="position:absolute; left:285px">*<?php echo $_SESSION["passwordErr"];?></span>
<br><br>
<button onclick="submitForm()">Submit</button>
</form>
<br><br><br>
<p><?php echo $_SESSION["flogin"];?></p>
</html>
<?php
session_destroy();
?>
Admin.php
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == POST)
{
if (empty($_POST["admin"])) // Check to make sure Admin field is filled out
{
$_SESSION["adminErr"] = "Admin field must filled"; // Set error if not filled
header("location:login.php"); // Return to login page
}
}
?>
Don't destroy the session at the end of the file..
</html>
<?php
session_destroy();
?>
Also you should put exit; after each header('Location: ...');.
When sending the header, the browser recognized to change the location but the script does not end. The browser in fact, would not even have to follow the header, it can also just go on with the script. You have to stop the script because the headers do not exit the script.
instead of
<button onclick="submitForm()">Submit</button>
use
<input type="submit" value="Submit">
Then put a check before echoing
<?php echo isset($_SESSION["adminErr"])? $_SESSION["adminErr"]: "not set" ;?>
further debugging:
var_dump($_POST);
var_dump($_POST["admin"]);
var_dump($_SESSION);
var_dump($_SESSION["adminErr"]);

Wordpress Screets Plugin and Ajax Login

Currently I am using Screets Wordpress Sessions Plugin and using a custom login form [because I don't want to use WP_users database and Wordpress's Admin for Users. I have my own reasons behind this.]
My login setup works perfectly except for the fact that Wordpress removes sessions and I for one do not want to hack at the core files for being at risk during an update. Below is my setup:
Login Form:
<form method="post" action="" id="login_form">
<div align="center">
<div >
User Name : <input name="username" type="text" id="username" value="" maxlength="20" />
</div>
<div style="margin-top:5px" >
Password :
<input name="password" type="password" id="password" value="" maxlength="20" />
</div>
<div class="buttondiv">
<input name="Submit" type="submit" id="submit" value="Login" style="margin-left:-10px; height:23px" /> <span id="msgbox" style="display:none"></span>
</div>
</div>
</form>
Ajax Script
<script>
$("#login_form").submit(function(event){
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
//check the username exists or not from ajax
$.post("<?php echo get_stylesheet_directory_uri(); ?>%page%.php",{ username:$('#username').val(),password:$('#password').val(),rand:Math.random() } ,function(data)
{
if(data=='yes') //if correct login detail
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Logging in.....').addClass('messageboxok').fadeTo(900,1,
function()
{
//redirect to secure page
document.location='/my-dashboard';
});
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Your login detail sucks...').addClass('messageboxerror').fadeTo(900,1);
});
}
});
return false;//not to post the form physically
});
</script>
DB Link
$username= mysql_escape_string(do something to username);
$pass= mysql_escape_string(do something to pass);
//now validating the username and password
$sql="SELECT username, password FROM %table% WHERE username='".$username."' AND active='1'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//if username exists
if(mysql_num_rows($result)>0)
{
//compare the password
if(strcmp($row['password'],$pass)==0)
{
echo "yes";
//now set the session from here if needed
$array = array(
'username' => $row['username']
);
$session->set_userdata( $array );
//$_SESSION['username']=$username;
//$_SESSION['loggedIn'] = 1;
}
else
echo "no";
}
else
echo "no"; //Invalid Login
Code works great except for the bit
$array = array(
'username' => $row['username']
);
$session->set_userdata( $array );
This is the only way to set a session with the plugin, but I get a error "Call to a member function set_userdata() on a non-object." Is there another way of going about this with my current setup or a way to correctly enable the default PHP sessions?
Thanks.
I think you must use
$sql="SELECT username, password FROM %table% WHERE username='".$username."'
AND active=1";
AND
if(is_object($session)) $session->set_userdata( $array );
AND
http://codecanyon.net/item/wordpress-sessions-plugin-with-database/3405722

PHP $_SESSION array populated in one div and empty in another

OK...i have something which makes no logical sense and I hope someone can point out the silly mistake I am making. I have a page in which i want the menus to change whether a user is logged in or not. I am using a session variable $_SESSION['is_logged_in] to store the logged in status. So for example, if logged out, the menu should say login. If logged in, the same menu should say logged out. Here is the code in logical pieces. I apologize in advance for all the code snippets but I want to be as clear as possible. Please help!
First, i have the main page called index.php which has some empty divs:
<div id="wrapper">
<div id="header">
<h1>My Page</h1>
<div id="navigation">
</div> <!-- end of navigation div -->
</div> <!-- end if header div -->
<p> </p>
<div id="mainContent">
</div><!-- end mainContent div -->
</div> <!-- end wrapper div -->
In this page (index.php), i have a jquery load of the navigation div on document ready:
<script type="text/javascript">
$(document).ready(function(e) {
//load the default menu
$('#navigation').load("menu.php");
});
</script>
OK...now menu.php has the following html/php:
<?php
session_start();
include 'php/functions.php';
//following is for debugging, you will see later where this is useful
if (is_logged_in())
{
echo "logged in value: " . is_logged_in() . "<br />";
print_r($_SESSION);
}
else
echo "not sure what is going on</br >";
echo "<br />";
?>
<ul id="menu" class="DropdownMenu">
<li class="sub">Account
<ul>
<?php
//this is where it should show one link or the other based on the value in $_SESSION
if (is_logged_in()) {
echo "<li>Log Out</li>\n";
} else {
echo "<li>Log In</li>\n";
}
?>
</ul>
</li>
</ul>
Ok...at this point, when the page loads, on top of the menu i see the debug message "not sure what is going on here" as expected because i am not logged in yet. Then I click on the Login link and via ajax, it populates the mainContent div in the index.php:
This is in menu.php:
$(document).ready(function(e) {
var options = {
target: '#mainContent', // target element(s) to be updated with server response
success: reloadMenu, // post-submit callback
delegation: true
};
// post-submit callback
function reloadMenu(responseText, statusText, xhr, $form) {
$('#navigation').load("menu.php");
};
//set the jquery form plugin for the login form
$('.ContentForm').ajaxForm(options);
//load the login form in the mainContent div
$('#wrapper').on("click", ".ClickLogin", function(e) {
$('#mainContent').load("login.php");
});
});
The above code shows that when the form is submitted, on success, the post submit callback should be re-loading the menu just like the initial load on the index.php document ready. With debugging, i do see that the it does reload it, but it never sees anything in the session variables so even though i am logged in, it still shows the Login link instead of log out.
Now, bringing it all together just to show i am not crazy, here is what is in the login.php:
<?php
// start the session
session_start();
include 'php/functions.php';
//this sections handles the post of the form
$show_form = true;
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$email = $_POST['email'];
$password = $_POST['password'];
if (authenticate_user($email, $password)) //this will set $_SESSION variables
{
$show_form = false;
echo "Congratulations " . get_user_name() . ", you are logged in <br />";
//following is for debugging, you will see later where this is useful
if (is_logged_in())
{
echo "logged in value: " . is_logged_in() . "<br />";
print_r($_SESSION);
}
else
echo "not sure what is going on</br >";
}
else
{
echo "Invalid email or password. Try again <br />";
}
}
?>
<?php if ($show_form) { ?>
<div id="formContent">
<h2 class="ContentHeader">Log In</h2>
<form id="contentForm" name="registration" class="ContentForm" method="post" action=<?php echo $_SERVER['PHP_SELF']?>>
<p>
<label for="email">Email:</label>
<input type="email" name="email" id="email" required="required">
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required="required">
</p>
<p>
<input type="submit" name="insert" id="insertLink" value="Submit It" />
<input type="reset" name="cancel" id="cancel" value="Reset" />
</p>
<p>Forgot Password? Click here</p>
<p>Need to Register? Click <a class="ClickRegister" href="#">here</a></p>
</form>
I know it is a lot of code so i want to point out one thing. At this point, when the form is submitted, in the #navigation div, the menu.php is reloaded and in the #mainContent div, the login.php is reloaded. Both are executing this exact same code:
//following is for debugging, you will see later where this is useful
if (is_logged_in())
{
echo "logged in value: " . is_logged_in() . "<br />";
print_r($_SESSION);
}
else
echo "not sure what is going on</br >";
When the page displays after the login form submit, above the menu it says "not sure what is going on" followed by "Array()", however in the mainContent, it shows "logged in value: 1" and prints out all the session values.
Just for completeness, the is_logged_in() function looks like this:
//return true if the current session is logged in
function is_logged_in()
{
if (array_key_exists('is_logged_in', $_SESSION))
return $_SESSION['is_logged_in'];
}
I have session_start() in both menu.php and login.php, if i didn't it gives me all sorts of other errors when trying to access the $_SESSION array.
I really hope someone can spot my mistake. Please help!
Thanks in advance.
Answering the question officially for closure. As mentioned in the comments above, I was destroying the session prior to setting it as part of the login. I am still not sure why that had the effect it did since both divs were loaded after the destroy/re-create but maybe there is some ajax race condition.
I am just glad it is solved and I can move on. Thanks to all for your input.

Categories