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

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.

Related

How do I get my $_POST to recognize the values

$_POST won't recognize the value mailuid from the login form on this page or others (profile page).
$_Get methods do not work because of how the login system is built and unsecured.I need mailuid value to bring them to their own profiles page after login.
Login Form since its's post method I should be able to grab the value on other pages and this one
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php
if (!isset($_SESSION['Id'])) {
echo'<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>';
} else if (isset($_SESSION['Id'])) {
echo '<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
}
?>
</section>
</div>
</div>
Temporary check for the mailuid value. Supposed to grab the value form the login form a spit it back out, to check to see if it is recognized
<?php
$user = $_POST["mailuid"];
if (isset($_POST["mailuid"]))
{
$user = $_POST["mailuid"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
?>
First I would clean this up:
$user = $_POST["mailuid"];
if (isset($_POST["mailuid"]))
{
$user = $_POST["mailuid"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
Instead it can be written more concise:
$user = isset($_POST["mailuid"]) ? $_POST["mailuid"] : false;
if( $user ){
echo "{$user} is your username";
} else {
echo "no username supplied";
}
I prefer Boolean false over NULL, null just means it doesn't exist. Boolean false lets you know you checked it and it didn't exist. Generally should should access $_POST as few times as you can. This is because you should never trust $_POST.
$_Get methods do not work because of how the login system is built and unsecured.
Post is no more secure than get, it's quite easy to post anything to the page even without visiting the site by using something like PostMan etc. Once you assign it to a local variable you know you have at least normalized the data, even if you haven't sanitized it yet.
Also don't forget to call session_start before trying to access $_SESSION. Because of the vagueness of the question, it could be that the form works fine, just the session data isn't being maintained because you haven't started the session yet.. etc....
Hope it helps.
Personally I would clean up the HTML part that makes the form as well, so instead of this:
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php
if (!isset($_SESSION['Id'])) {
echo'<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>';
} else if (isset($_SESSION['Id'])) {
echo '<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
}
?>
</section>
</div>
</div>
I would do something like this:
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php if (!isset($_SESSION['Id'])){ ?>
<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>
<?php }else{ ?>
<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
<?php } ?>
</section>
</div>
</div>
See how much cleaner that is. Most of this is just readability issues. For example there is no need to check if isset($_SESSION['Id']) in the else if condition, because it's either set or not. This is one less place to maintain the session variable key, and it makes the code less convoluted.
As for the actual problem, as long as you are reaching the above code after submission of the form, it should work. So that leads me to believe that you have something wrong in the action.
You should get a clean page after going to includes/login.inc.php meaning there shouldn't be much in the way of HTML. One thing you can do that is real simple is just add at the top:
die(__LINE__.' of '.__FILE__);
$user = isset($_POST["mailuid"]) ? $_POST["mailuid"] : false;
//... other code
What this will do is die which kills PHP execution, but outputs the argument you passed in. In this case I'm just putting the line and file that the die is on, that way it's easier to find later. But the point is to see if you are even hitting the correct ending script or the forms action/endpoint.
I only suggest this because you are really vague in what it's current behaviour is
$_POST won't recognize the value mailuid from the login form on this page or others (profile page).
For example, this doesn't tell me if you are even hitting the right page. Now had you said something like "all it does is output no username supplied". Then I would at lest know that. As I said above it could be just an omission of sesion_start() which must be called before attempting to access any $_SESSION stuff. You should call it only once, at the top of each page that uses sessions.
Although it's not a solution, it was too much to post in a comment. I would really like to help you more, but there just isn't enough information to go on.

php page accessible only by passing through another php page

I am looking to develop a website containing stages. I want for example to pass by the stage 2 only when i click on the finish button in the page of stage 1 so the stage 2 page can't be accessible by its url or whatever only if the user pass by another page.
Is there a method to do this ??? i am a beginner in security so please try to help me, thanks in advance coders
Make use of sessions to develop this model.
index.php
<?php
#extract($_POST);
if(isset($sub))
{
session_start();
$_SESSION['authenticate']=true;
header("location:test1.php");
exit;
}
?>
<form action='' method="post">
<input type="SUBMIT" name="sub" value="Finish" />
</form>
open.php
<?php
session_start();
if(!isset($_SESSION['authenticate']))
{
echo "You are not allowed to access";
}
else { echo "You came from index.php ! so you are a valid user"; }
session_destroy(); //<-- I added this so you can test your example multiple times.
I think, this show work :)
Use can either redirect your user directly from index.php to open.php
header('Location : open.php');
Or,
in open.php, put this
if($_SERVER['HTTP_REFERER'] == 'index.php page's full link') {
//Do or Show whatever you want to show here
} else {
// Tell the user that you are not authorized
}
If that doesn't work, echo $_SERVER['HTTP_REFERER'] and see what link it gives you. And put that link where specified above.
Cool? :)
Edit (As per the comments) --
Lets say you have a form in your form in stage1.php
<form method="post" action="">
<span class="error"><?php echo $error; ?></span>
Name: <input type="text" name="name"><br/>
Email: <input type="text" name="email"><br/>
<input type="submit" name="submit" value="Submit">
</form>
use this php in stage1.php
if (isset($_POST['name'])||isset($_POST['email'])) {
if (!empty($_POST["name"])||!empty($_POST["email"])) {
$error = "Please fill in all the fields correctly";
}
else {
$name = $_POST['name'];
$email = $_POST['email'];
//You can also save the above Variables Globally by $GLOBALS['name'] = $_POST['name'];
//So that you can use the details when you reach the final stage
header('Location : stage2 page's link');
}
}
?>
and in Page 2 lets say you have another form, then there also check
<?php
if(!empty($name)||!empty($email)) {
//the above is check for global variables email and name are not empty - means stage 2 was filled properly
//Do things for the second page's form like you did for stage 1
} else {
header('Location : stage1 page's link');
//redirect back to stage 1.
}
?>

Form not displaying for logged in users

Please i need your help with my script. I'm trying to post comments to news items on sections on my website only for users who are logged in. If they are not, they are shown a link to Login or Register, and the "Post A Comment" inputbox does not display.
Then when they login the form should display.
The form does not display, when they are not logged in, but it does not also show the form when they are logged in.
Please where could the broblem be.. Thank you for your time and patience. I apppreciate it.
<?php
if (!isset($_SESSION['username'])) {
echo "Login OR <a href=\"register.php\">Register</ a> to make a comment" ;
}
exit();
?>
<?php
if (isset($_POST['submit'])) {
//process form
}
?>
Post A Comment <br/>
<form action="<?php echo $_SERVER ['PHP_SELF']; ?>" method="post">
<textarea type="text" name = "comment_body" title='Post A Comment' class='OpenInput_Text' ></ textarea><br/>
<input type="submit" name="submit" value="Post Comment">
</form>
</div>
</div>
You will need to start your sessions.
Replace
<?php
if (!isset($_SESSION['username'])) {
With
<?php
session_start();
if (!isset($_SESSION['username'])) {
.. It's because you are exiting the script in with an
exit();
I think you want to push it one line up, to end the script if the user is not logged in.
Move the exit() inside if (!isset($_SESSION['username'])) { ... } instead of after it.

A popup box on page load

I am using a feature of popup box in my project. When a user come to the site a popup box apears on the top of the page hiding the rest of the content. In that popup form the user has to give a download key. if the user has the key he can go forward otherwise he cannot see anything else. When the user provide the key he goes to the main page.
Now the problem is once the user comes to the main page after providing the key and when he clicks again on the header again the page is reloaded and again tht popup form comes. How can I prevent it to apear again if some user has already given the download key . I am using php with code igniter. My code
<?php if($download_key != null && !isset($_POST['popup'])){?>
<script type="text/javascript">
$(document).ready(function(){
loadPopup();
});
</script>
<?php } ?>
downlaod key is database column and popup is a hidden input that is set when the form is submitted on the popup box.
The form that appears on popup box is as
<form name="form" method="post" onsubmit="return validateForm('<?php echo $download_key ?>')">
<div style="width:530px;">
<input style="display:none; height:25px;" id="downloadkey" name="downloadkey" type="text" />
<input style="display:none;" type="submit" id="submit" name="submit" value="<?php echo $variable['QUESTION_BUTTON']['value']?>"/>
</div>
</form>
Any ideas ?
Thanks
You should have a session_start() at the beginning of pageload
EDIT: changed a bit
session_start();
//check if key has already been seen:
if(isset($_SESSION['download_key']) && $_SESSION['download_key'] != null ...
// then if not check if the key is submitted
else if ( isset($_POST['popup']) ... // and other checks
// set session variable
$_SESSION['download_key'] = $key;
else
// load the ask for key page
Set a session variable, and check to see if it's present, as it will be on subsequent pageloads, and just skip the popup etc.
<?php
session_start();
if ($download_key != null && !isset($_POST['popup'])) {
if ($_SESSION['key_ok']!=true) { //you should check if it's set first with isset()
echo '<script type="text/javascript">';
echo '$(document).ready(function(){';
echo 'loadPopup();';
echo '});';
echo '</script>';
}
if (key_is_correct) {$_SESSION['key_ok']=true}
}
?>

PHP sessions not being set

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

Categories