I am going crazy and need some tips and help. Working with custom cms and php programming language. I am working on online site on server.
Problem is next:
Session start is ok, In functions.php I start session['lng'] and put _LNG constant in it and it's ok, passing alright.
When I call session['lng'] in my other files I always get the same language constant (en) but I am passing (hr) or (de)?? I checked 10 time if session is set somewhere else but it isn't.
How can I check where's the problem...I really don't know what to do next
Did you place this at the start of other files before accessing session variables. It's required to access session vars.
<?php
session_start();
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.
I'm curious to know exactly when the session text file is created? An easy and surface level answer to that would probably be,.. well, when you use session_start(). But is it?
Could it be all the way at the end when the php script ends?
What makes me think that it may be at the end is that I know PHP would not write to the session file everytime you make a change to a session variables while the execution of the page goes on. For example, if you got something like $_SESSION['x'] = $_SESSION['x'] + 1; in a loop, the session file does NOT get modified at each and every iteration of the loop. Only when the PHP scripts is done, then the PHP engine makes a change into the file, to store the final value of the $_SESSION['x'].
With the same taken of logic, I see no reason for PHP engine to create a file as soon as you call the session_start. It could just delay the process.
What that entails is this;
I can start a session with session_start(), set a few session variables, toss them around within functions, using them as globals, and at the end of script, I unset them, and destroy the session and as a result, I assume NO SESSION FILE IS CREATED, thus no overhead associated with creating the session text files is experienced.
I would like to hear your insights in this.
My purpose is to explore the possibilities of using session variables strictly as a temporary place holder to pass global variables left and right - without dealing with file I/O. In fact, I do not need those variables in the next page at all.
In this case, could sessions prove faster than using globals within functions?
Tested and it gets created immediately on session_start. However, session_destroy removes it too. Tested with:
mkdir sess && cd sess
vim main.php
session_save_path(dirname(__FILE__));
session_start();
sleep(5);
session_destroy();
php main.php &
ls # main.php sess_rm4bcun6ear943mf61mdads190
fg # wait for script to end
ls # main.php
There's the answer to your question. Your idea of using _SESSION for global variable purposes is not a good one .. you might as well juse use $GLOBALS. No file IO there.
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”.
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.