JavaScript redirection problem with PHP sessions - php

I set a session variable on login subdomain, and response json from another subdomain if the login was successful, the responsed json is checked by a script and the script does a location.href = "new url". On the redirected site "new url" I want to check my session variables if the user is logged in or not, but there are no session variables set. Does location.href = "" destroy my session? How to fix this problem? session.cookie_domain is set to '.mydomain.com'.
login.mydomain.com:
$.post('http://api.mydomain.com/index.php', {action: 'login', username: username, password: password}, function(response) {
var success = $.parseJSON(response);
if(success.success == 'true') {
location.replace = 'http://my.mydomain.com';
}
});
api.mydomain.com:
session_start();
$_SESSION['active'] = true;
header('Access-Control-Allow-Origin: http://login.mydomain.com');
echo '{"success": "true"}';
my.mydomain.com:
session_start();
if(!isset($_SESSION['active']) && !$_SESSION['active']) {
header("Location: http://login.mydomain.com");
echo $_SESSION['access_token'].' test';
}
else {
echo 'Success!';
}

I had the same problem and I found when I use a relative url (location.ref="index.php"), all sessions variables exists. But when I use a absolute url (location.ref="http://mydomain.com/index.php") it kills all my session variables.

You don't seem to be calling session_start() in the second code block.

From what you're saying you could have a couple of issues contributing to this problem.
PHP cookies are set by the server when the page is loaded, no page load means no cookie is set, if you're using pure JSON with no page load then you may not be able to set your session and return it to the browser.
Also remember that PHP sessions are effectively a cookie and the rules for cookies apply, so if you're setting a PHP session at api.mydomain.com and expect it to work at my.mydomain.com it probably wont work.
You can find a viable solution to handling login data and the sessions over multiple sub-domains here

Related

PHP Cookies not being loaded when coming from a clicked link

I'm working on a website that is keeping a user session token in $_SESSION. When I type the URL directly, I can load the cookies just fine, but when I click on a page that loads the cookie through PHP, it can't find the cookie. Is there any way to get around this?
Here's the code for saving the cookie
setcookie("tpl_token", $token, time()+365*24*60*60, "/");
And for retrieving
if(isset($_COOKIE['tpl_token'])){
$token = $_COOKIE['tpl_token'];
} else {
echo "Cookie not set";
}
It is returning that cookie is not set.
In order to create a session in PHP, use the session_start() function. PHP handles sessions internally for you, so you do not have to do any dirty work.
Example:
session_name("tpl_token");
session_start(); //sends session cookie with name "tpl_token"
//create session variable.
$_SESSION["logged_in"] = true;
if(isset($_SESSION["logged_in"])){
//stuff to do if user is logged in already
} else {
//stuff to do if user is not logged in.
}
//Destroy Session/Logout;
session_unset();
session_destroy();
If you are try create session cookies, there is no need for the $_COOKIE[] function

How to prevent a user from directly accessing my html page by writing URL?

i want a hard coded Login Page (login.html), with no database.
If a person writes correct username and password, it redirects to (page2.html).
Now my problem is that if a person write the URL directly for page2.html , he will be able to access it, without any login.
Ideal Case => www.example.com/login.html => if Correct => www.example.com/page2.html
Problem Case => www.example.com/page2.html => page2.html , NO LogIN :(
You can control all this with a php session like this
//set the session on the login page
$_SESSION['loggedIn'] = true;
//on the second page you check if that session is true, else redirect to the login page
if($_SESSION['loggedIn'])
//allow
else
//redirect to the login page
header('Location: /login.html');
A session is a way to store information (in variables) to be used across multiple pages. By default, session variables last until the user closes the browser.
To make things simple, you can change your pages into php (e.g login.php).
Line 1: In your login.php page, you will first check if the username and password are correct, if they are, set the $_SESSION['loggedIn'] = true
Line 2: In your second page (page2.php), you will first check that the user did login by checking if the session have a value if($_SESSION['loggedIn']) {//allow processing}
Line 3: If that session variable is empty, then this means the user did not login, redirect him to the login page else { header('Location:/login.php');}
To start off: I have no idea how you would like to compare the password and username with something and check whether it's correct or not, but for now I would do something like this (again, this is without database).
You have 2 options: Either use a session as stated above, or the bit easier way: Just use theisset() function.
<form action="page2.php" method="POST">
<input type="text" name="userName" required>
<input type="password" name="password" required>
<button type="submit" name="submit">Send!</button>
</form>
page2.php will contain the next code:
if(!isset($_POST['submit']) {
//direct back to a certain page, could look like this:
header('Location: xxx.php');
exit();
//exit() prevents the code from running, it litterly EXITS the code as soon as it hits that line.
} else {
//direct to page2.php
}
Let's break it down: Why did I use the extension .php? Because you cannot do this purely with HTML.
Why did I use (!isset()) instead of isset()? Because a good practice is to think in security first, you don't access an important area and THEN check whether someone has lethal weapons or not. You check first and then you allow him either in or denie access. This is a quite simple and common way to prevent someone from accessing your page with the URL, however a SESSION is better and a bit more experienced practice.
This problem cannot be solved with a pure HTML solution. Your question is tagged as php so I'll base my answer on that:
Post your form to a php script (such as login.php)
Script checks the login details and sets a cookie
page2.html must be php instead, and checks for the cookie before displaying the HTML
Another option is using HTTP authentication, see this article for a tutorial.
You could block that page's access from external locations in your server securtiy settings,
then send the html of that page to the browser on successful login with fil_get_contents('page2.htm') in php. the php is run on the server so the file request won't be from an external source. you could overwrite html on the page using javascript or you could echo the contents on an if in php that will show the normal page on else
eg
if(isset($_GET['Login'])
{
//check login details
//if(....) //put your login check logic here
{
echo file_get_contents('page2.html');
}
else
{
//normal page's code goes here
}
}
Note:how to set the file to disallow external access is outside the scope of my answer
I had the same problem and found this and it works perfectly: (in javascript)
Just put it at the top of the document.
var x = document.referrer;
if (x == "page2.html") {
console.log(x);
} else {
window.location.href = "login.html";
};
change the default path for your website by using complete path to login.php. Next time when any of the user will type your url, they will be redirected to the given path which is yourpath>login.php
Hope it will help.
If you are using Asp.net, perhaps you can use TempData. They stay with the session between pages.
if (/*username and password are correct*/){
TempData["LoggedIn"] = "True";
} else {
TempData["LoggedIn"] = "False";
}
Then, when your controller tries to load page2 you just check the value of TempData.
var validate = TempData.Peek("LoggedIn");
if (validate == null || validate.ToString() == "False"){
return RedirectToAction("login");
} else {
/*allow access to page*/
}
Using .Peek keeps the TempData, as it would normally be marked for deletion if it was accessed. You also want to check it for null as it may have never been assigned if the user does not first go through the login page.
You can prevent that by checking if the user is already logged in
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
header('Location: login.php'); //here you put your login page
exit;
}

PHP detect if session cookies are disabled

I know that with sessions in php, a cookie that stores the session ID is set on the client's side. The client can turn off these cookies, which I presumes makes sessions not work. How can I detect if the client has disabled the session cookies?
You can use javascript navigator.cookieEnabled. This returns true or false.
So
if(navigator.cookieEnabled)
//do something
else
//do something else
assuming you started a session on a previous page...
<?php
if(session_status() == PHP_SESSION_ACTIVE)
{
echo 'cookies & sessions enabled';
}
else
{
echo 'no cookies or sessions';
}
?>
or you're looking for a non-session cookies as well.
<?php
if(!empty($_COOKIE))
{
echo 'cookies are tasty';
}
else
{
echo 'no cookies to eat';
}
?>
with a pure php solution you can't check if sessions/cookies are enabled without setting a cookie on a previous page
If you know you MUST use a session, the usual approach is to redirect the user instantly at the start while trying to set a cookie, and then complain about the cookie not being set on the second page.
User goes to http://www.example.com
System sets a cookie (maybe only starts the session, maybe a dedicated test cookie).
System redirects to http://www.example.com/?cookietest=true
On that page, if the cookie is not sent back, complain to the user.
On the other hand, most of the time a session really is not needed if you do not have to log someone in. And IF you do, most users will understand they need to allow cookies, because otherwise the login will fail.

Session destroy every time when page refresh

I am making admin panel there I implement login area when all information match to the database i mean login information username and password than i start session and redirect to index page but extremely confused why session null when i page refresh actually on index page i check that if session null than page redirect to login page.also using session_start(); on every page.i have been checked php.ini for lifetime there life time set 1440 default.
checking.php
session_start();
if((!empty($result)) && (!empty($result2))){
$_SESSION['admin'] = $user;
header("location:../../index.php");
}
else {
echo "Something wrong";
}
index.php
<?php
session_start();
if($_SESSION['admin'] == null)
{
header("location:system/access/login.php");
}
require('../config.php');
require('system/classes/userdata.php');
?>
Any one now the solution.
checking.php
//session should be started before every thing.
session_start();
if((!empty($result)) && (!empty($result2))){
$_SESSION['admin'] = $user;
header("location:../../index.php");
}
else {
echo "Something wrong";
}
maybe its because of the null thing, try this
if(isset($_SESSION['admin']){
//write your code
}
Reason being that a NULL is not equal to a NULL
#Mubo, session should not be started before everything, especially if you store objects in session.
#user3163274, this can be problem with sessions configuration, it can be badly configured cookies, or perhaps you got session cookies disabled at all (by default cookies are enabled). Problem can be caused by data you hold in session (especially if you hold there objects).
But if i can suggest, stop using relative paths for includes/requires and redirections. Also, if you want to test data against nulls use equality operator like === (it also checks the type)

PHP login session wont work on first page load in a NEW window with no cache

I am working on creating a website from scratch and am currently stuck with session stuff.. I know generally how sessions work and how to store things into $_SESSION after session_start() but my main problem is this. After clearing the cache and opening a new window, submitting a login request the FIRST time wont submit correctly and the page reloads and nothing has changed, but AFTER the first time, it works fine...
my login.php handles either a) the post request, or b) the login via url (for testing purposes) so a link to "user/login.php?username=facebook&method=get" would be sent to the code below and set the user to logged in with the name facebook..
<?php
session_start();
$method = $_GET['method'];
if($method == "get") $_SESSION['username'] = $_GET['username'];
else $_SESSION['username'] = $_POST['username'];
header('Location: http://www.imggroups.com');
?>
Im not sure if this matters, but, on the index page, I check to see if the user is logged in by doing this. starting session obviously, then doing. if(isset($_SESSION['username'])) echo whatever i need for logged in.. else echo whatever for not logged in.....
The issue is that you are redirecting the user to a new page, but the old page has not finished closing, so the session is not yet saved.
In order to fix this I usually setup an interum page which redirects to the correct page.
Alternatively you might be able to use session_write_close() (http://www.php.net/manual/en/function.session-write-close.php) before using the header redirect
The fact of the matter is, it is setting the session, BUT it's redirecting you to a different domain that the session isn't allowed on. If you access the website without the 'www.' in front then get redirected to the www version afterwards, then it's going to say your session doesn't exist. Use the following:
session_set_cookie_params(0, '/', ".imggroups.com");
Put it before your session_start() and it will work for both www and non-www versions of your site.
If that is the total of the login.php, I believe there is easier ways to do that:
If it does not matter whether the username actually comes in via _GET or _POST, then use _REQUEST as it encapsulates both.
if( isset($_POST['username'] ) {
$_SESSION['username'] = $_REQUEST['username'];
}
If it does matter, you don't have to trust or use an external parameter, just look at what's there:
if( isset($_POST['username'] ) {
$_SESSION['username'] = $_POST['username'];
} else if( isset($_GET['username'] ) {
$_SESSION['username'] = $_GET['username'];
} else {
// whinge
}
I've not run into that issue with PHP before, but you can also do a session_write_close(); to force it to write out the session before it redirects to the other page.
I also had this same issue if i open new window after logout in new tab or browser and try to log in login page stuck at loading i can see that session has been started because if i refresh on same stuck window i logged in to my dashboard.
But it was resolved later by redirecting it right:
Before
login.php (after ajax successful) --> index.php (if logged in) --> dashboard.php
After
login.php (after ajax successful) --> dashboard.php
hope it saves anybody's time & effort because i suffered alot!

Categories