PHP session doesn't seem to persist across web pages - php

I set a PHP session global on one web page, go to fetch it from another and it isn't there....
I have read up on all the standard pitfalls and have made sure they're not the issue:
– Web pages end in .php,
– First line:
<?php
if (session_id () === "")
{
session_start ();
}
?>
– Etc....
My best guess at this point is that perhaps it is because I assign the session variable from one domain (http://www.foo.com) and then call through to a PHP executable on another (https://api.bar.com) and ... maybe I get a different session ID? These domains are on the same server though.
I guess my question is, are sessions scoped to the domain in question in PHP?
(I kind of wanted to have all my PHP scripts on my one domain with the secure transfer protocol — I'm too cheap to get a certificate for every domain I own).

Related

PHP - Issues with session variables

I'm having an issue on my website. I'm not posting any code because I don't think there is anything relevant to show and I've done things alike several times. My question is just about logic.
I have a page that sends ajax requests to two other php files. These files use session variables to build some JSON.
The problem is some session variables are seen only by one php file. When I check the output of var_dump($_SESSION) I can see that one file sees all the session variables, and the other one can only see the ones it has set in the previous calls. When I check the session IDs, I can see that both files have different session IDs.
Do you have any idea about what could be the problem, or just tracks to follow?
check whether you have session_start() in both pages before using the sission variables
I finally solved it. The problem was linked to the domain name. When you use subdomains, or don't add "www", the browser thinks it's a different domain and doesn't send the cookies, then a new session is initiated.

php session sometimes not avaliable after passing to another domain

I run a website which can be reached through different domains: domainname.de, domainname.ch, domainname.at, domainname.es etc. ...
When my customer wants to pay we gets to a payment page which is of course https secured. Due to server limitations I am only allowed to have one SSL Certificate which I only put on one domain: domainname-secure.com.
Because I charge different prices I need to know which domain the user belongs to, so when redirecting to domainname-secure.com I save the domain (e.g. domainname.de) in the session variable $_SESSION['domain_default'] and pass the sessionID by adding session_id=[session_id] as a get parameter.
Then I check I take $_GET['session_id'] and run the follow command to have the session available on the domainname-secure.com:
session_id($_GET['session_id']);
session_start();
When I test it myself, it works perfectly fine but I make a log entry when somebody gets to domainname-secure.com and has not have set $_SESSION['domain_default'].
This occurs several times a day but I really have no clue why this does not work! I am testing it again and again from many different links but for me it works perfectly fine.
Can some of you imagine why it sometimes does not work?
Is it not "good" or insecure to pass the session ID to another domain and is it not always readable after redirecting?
I know it is hard for you to determain a mistake but I am searching for some know issues with session or maybe a tip how to do it in a better way?
Session are administered by PHP on a per domain basis meaning they don't mix domains intentionally.
If you would be using another session storage mechanism such as writing into the database or using memcached sessions you'd be able to overcome this limitation.
There are two approaches if you want to be able to access the session info when changing domains either:
Don't use PHP's $_SESSION, setup your own session management with memcached/redis/sql;
Or:
Use PHP's $_SESSION, but when transferring from one domain to another serialize the data in $_SESSION and put it somewhere accessible from both domains like sql;

PHP Sessions basics

Ok, i have one totaly noob question about php sessions:
I have 3 (and more) php pages, i need to protect them with login system and sessions. Now, i am including this to the top of every page:
session_name('somename');
session_start();
if(!$_SESSION['user_loggedIn']){
header("location: login.php");
}
if (isset($_SESSION["timeout"])) {
$inactive = 900;
$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
session_destroy();
header("location: login.php");
}
}
Question: is it correct to add something like include session.php; to top of every php file, ofc. session.php would include only code above.
You shouldn't need to handle the session timeout yourself, your webserver is almost certainly handling that for you already. All you should need to do is check to see if the session exists and make sure you have login info in that session.
Also, as far as "what's the right thing to do" -- if you require it at the top of every php file, remember to use "require_once" because there's no point in doing the same thing over and over if you include other files. Also, you may only need to do this on pages where you know you only want secured users, which isn't always every page of the site.
PHP is a programming language that is similar to JavaScript but allows for better functionality of the code to develop dynamic websites and apps. PHP stands for Hypertext Pre-Processor. In this tutorial, I will walk you through what a session is, how to declare session variables, and introduce you to a few functions that will allow you to get your session up and running in the way you need it to.
What Is a Session?
First, you may be asking yoursslef, “what is a session?” In this programming language, a session is “used to store and pass information from one page to another temporarily (until the user closes the website).” If you are familiar with cookies, sessions are a very similar topic. While cookies are only stored on the local computer and browser that you use, sessions get stored on your machine as well as on the server you’re using. Both of these collect information about the way you interact with the webpage to improve the experience for a user. To summarize the two of them, “data that is kept in cookies is solely kept on the client’s side, whereas the information kept in sessions is kept on both the client and server’s sides.” (The link to the article I found this can be found here).
The most common functions that you will use as you begin to learn PHP are the session_start() function, the die() function, and the session_destroy() function. These three functions allow you as the user to start specific tasks and then stop them whenever you want. The session start function will allow you to, of course, start a new session. The die() function will allow you to clear any session variables that you may have used during your session, and the session_destroy() function will end your session. Now, understanding what a session is, let’s discuss what a session variable is and how you can declare them.
What Are Session Variables?
Session variables make it possible to make sessions in PHP useful and functional. Which variables you use will be different depending on the project you’re working on, but in my project and database I used variables that helped me see the status of users on my database. I’ll share two examples (see screenshot below, lines 54-55). The two variables I declared here were “logged_in” and “username”. All session variables are declared with a unique syntax. The proper way to declare a session variable is as follows:
$_SESSION[“nameofvariable”] = “variable declaration”;
It is important that you declare your session variables in this syntax or you will not be able to have your sessions run properly. As a system administrator, these variables help me to see who is logged into the databases and making edits to tasks. In addition, the logged_in variable enables functionality of the database and webpage. If the user is not logged in, then the code knows to redirect the user to the login page. See the example below:
Screenshot 1:
I then used these variables to help me keep track of the state that my program and database were in to allow it to function properly.
Let’s Get To It: How to Set Up Your Sessions
Now that we understand more about what a session is and how session variables can help us accomplish our goal of a functioning program, let’s discuss the process as to how we can actually implement this. First off, go ahead and open up your IDE. I personally picked Visual Studio Code as it allows me to comfortably program with color codes, but you can pick whichever one you choose. In this example I will show you how I set up both of my sessions using a particular action that implemented my to-do list to my database. Although the code I will share will be specific to my project, the principles will remain the same for all PHP code.
In the screenshot at the end of this section I have some code I wrote at the top of an action file that ultimately ended up allowing a registered user on my webpage to sign into their to-do list. Because this was an element that required the database to be fully implemented, I knew that I had to use the PHP language. In this screenshot and in your code, you should start your code with the simple PHP starter code of:
<?php
That’s right! That is all you have to do. This allows your IDE to recognize what you will be coding in. Once it has this information you get to set up your session which, believe it or not is another easy step. In order to declare that you’re going to be starting your session all you need to do is declare the following code:
session_start();
In order to properly run your sessions, it is vital to know and understand that this HAS to be the first thing declared in your code document otherwise it will not function properly. Once this code has been declared then the computer knows to iterate through the code in your document until another function is called telling it to stop. Once your function is declared you have the chance to declare your session variables and any other information you need the computer to know. Here in screenshot 2 I have the visual example of me declaring my php language, starting my session, and declaring the variables that are unique to me that establish my connection from my to-do list to my database. This is my 2nd screenshot:
Screenshot 2:
From this example you can see from lines 1-16 of my action file. Everything that I did here is what was explained in this section.
Useful Tip:
Another function that allows you to properly manage your session is the die() function. I implemented this one in my file. It is a way for the script to be stopped while keeping your session open. This was useful to me because it was a way of letting my script know to stop and moving to the next portion of my instructions, which were found in another file. If you are coding a particular project that requires multiple actions, then this is a great function to keep in mind!
Destroying (Ending) a Session
The word “destroy” sounds pretty hardcore, but in PHP sessions destroy is just a word that means “end”. The syntax of this function within the session is the following:
session_destroy()
The destroy function will take any and all data that you used during your session and destroy it. However, it is important to note that it will NOT reset or delete any of the global variables that you may have declared during your coding. In order to start a session again you need to code your project to have the first function, start_session(), called again.
End Result
You may or may not be coding a database, but the steps that I listed above should be a place to allow you to learn the basic principles of what a session is, how to start one, declare variables, and end your session at the appropriate time. In my particular database project I was able to use sessions to allow users to login to a page, log out of their account, register a new user, to update actions included in the database, and more. Whatever your project may be, sessions have a great ability to adapt to the needs that you have as a coder. In the extremely rare event this tutorial didn’t answer every question that you have, I have also included a list of some additional links and videos that may help you answer any unanswered questions about sessions in the PHP language. Happy coding!
Additional Resources:
https://www.javatpoint.com/php-session
This website is a great resource for studying more about what a PHP session is and all basic information about what they do. This page also includes information on specific types of sessions, how to code them, how to implement them, and when they should be used.
https://www.tutorialspoint.com/What-is-the-difference-between-session-and-cookies
This is a great resource for understanding the differences between sessions and cookies, and for also seeing how they are similar. This website is comprehensive in how it compares the two features, even going into detail on their capacities, functions, data storage, and format.
https://code.tutsplus.com/tutorials/how-to-use-sessions-and-session-variables-in-php--cms-31839
This website does a deep dive more into what a session is and defines Session Variables for the PHP language. It goes into detail on how to start sessions and also talks about some common errors that may occur.
https://www.javatpoint.com/php-session
This link has outstanding information and further descriptions as to how to destroy, or end, a session. It also goes into further detail on what it will do to your project and code in addition to describing what it will not do.
https://www.youtube.com/watch?v=h6KID8n0zCU
This is a great video that describes sessions. I personally like to refer to it as “Sessions for Dummies”.

How to access session variables from a second php file?

As part of my attempt to create an ASP.net that has the same look and feel as an existing php application from another developer. (more about it can you read here: How to share sessions between PHP and ASP.net application?)
I'm in the middle of the process of sharing userlogin state between my ASP.net and PHP application.
I have links like signin.aspx?foo=asdhhjkasd (ASP.net) and signin.php?foo=asdhhjkasd which tell the other application which user credentials should be used for authenticating a user.
Right now I'm stuck with PHPs session management: The existing php application consists of a index.php which includes several (some out of 100) other php files and performs its function. There is a sessionmanagement (session_start() involved et cetera.
What I want to do, is to call a page call signin.php with some parameters. Based on whether the used logged into the php application before or not, I simply want to redirect to the index.php, but I can't get a hold of the session variables.
How must my signin.php look like, to access the session variables used in the index.php. This is what I tried so far:
<?php
// session_start(); tried it with or without it
if($_SESSION['user_id'] != "")
{
header('Location:index.php');
}
else
{
echo "no redirect";
}
?>
I always get "no redirect" printed.
Or is my thinking wrong and it is not possible to access the session variables from another page in php when there is no post/get action involved?
Maybe I should say that my PHP abilities are a bit limited.
Make sure you have the correct cookie name (the default is PHPSESSID). You can change it with session_name().
Also: you should call session_start(), so your code works even if session.auto_start is off.
Your script looks ok, I don't know why it would not work unless "session_start()" hasn't been initialized prior to using the sessions.
Also, where do you define the sessions? check that "session_start()" has been initialized there as well.

Having two different sessions in same domain

I run foo.com. I have two different applications that live in foo.com: one is foo.com/bar, and the other is foo.com/example. I use sessions to track information about the user while they're logged in, but if the user goes from foo.com/bar to foo.com/example, foo.com/example sees the session the user started from foo.com/bar and uses that information. My question is, how can I have two different sessions going for each directory at the same time?
You should call session_name before calling session_start. This sets the name of the cookie used to identify the session (by default this is PHPSESSID).
Use a different name for each application. You shouldn't have to mess with the variables inside the session.
I think it's very important to highlight the potential security implications associated with the solutions provided so far.
I have been a web application penetration tester for about 5 years and have developed numerous vulnerable security applications in this time to assist with training of juniors starting out in IT security.
I have just been testing the solutions provided and have noted that none of them prevent access to a session belonging to the neighbouring app. Using different session identifier names with session_name() doesn't prevent users from using the value of these identifiers. PHP doesn't have a segregated storage for each session identifier name. I had two apps using different session names and setting a cookie path for the browser. The following respective Set-Cookie directives were included in HTTP responses:
Set-Cookie: TESTONE=<value one>; path=/testone/
Set-Cookie: TESTTWO=<value two>; path=/testtwo/
If both apps had entirely separate users and someone only had access to the /testtwo/ app, they may be able to access info on the /testone/ app depending on the way in which session parameters were being handled. An example code segment below shows a potential data breach assuming that both apps use a $_SESSION["authenticated"] parameter after successful authentication.
<?php
session_name("TESTONE");
ini_set("session.cookie_path","/testone/");
session_start();
if ($_SESSION["authenticated"] == "yes")
echo $topsecretinfo;
?>
To access this $topsecretinfo one would only need to authenticate on the /testtwo/ application, take the value of their TESTTWO session identifier and use it as the value of the TESTONE session identifier when sending requests to the /testone/ application. PHP's session lookup process does not recognise the name of the session identifier except for parsing the correspoding value. i.e. a session identifier value of "agcy648dja6syd8f93" will return the same session object regardless of the name used to refer to it.
You may be able to use session_set_cookie_params to set the domain and folder for the session to be saved under. IE:
// Used on foo.com/example
session_set_cookie_params(86400, '/example');
// Used on foo.com/bar
session_set_cookie_params(86400, '/bar');
You could also use the same session but change the variable names that you look for.
Edit: Sorry this doesn't answer your question but gives an alternative solution.
Another solution is to effectively create a namespace within your session by pre-pending all session values from foo.com/bar with "bar_" and foo.com/example with "example_".
The way you can keep this from being tedious is to abstract this functionality into a function or class method. For example:
function set_session_value($key, $value) {
//figure out which prefix to use by checking the current working
//directory, or whatever method you like. set $prefix equal to
// "bar_" or "example_".
$_SESSION[$prefix . $key] = $value;
}
Then get your values with a matching function.
The main advantage of this is that you don't have to think about what variable names you're using in /example while programming in /bar. The other is that if you decide to change how you are storing session values, you can easily change everything in one place.
I realize this is old, but thought it might help someone. This example shows how we are setting a separate session for our admin area.
if ( $_SERVER['REQUEST_URI'] == '/admin/' ):
$session_name = 'session1';
else:
$session_name = 'session2';
endif;
session_start( $session_name );

Categories