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”.
Related
In my PHP application, I heavily use sessions to save information during redirection:
Saving information on category, so the correct tab and/or form is displayed after a redirection
Saving information when you are logged in to access some functionalities
Saving information on errors and warnings so they are displayed once all back-end operations are done and you are redirected to the main dashboard
In implementing that I called session_start in about 40 scripts, but outside of occasionally calling unset() on a $_SESSION variable I don't close the session in any way.
Now, while I was investigating performance issues on my server, it came to my attention that an underuse of session_write_close() might be the issue (even if the question was on an apache linux and my web app is hosted on a wamp server) and that in the end, even if it is not the cause, it might be sensible to try to close the session as soon and as often as I can.
I'm wondering how do I identify the points where I can safely destroy/restart the session? And what would be the best way to do that?
Keep in mind I want the number of opened session not being an issue, so I want to be sure to keep it at a minimum.
Typically we do not close session unless it is very important since session would be closed as soon as browser is closed.
Due to lack of knowledge of your application we are not in position to comment on exact need to close session in script. Considering the events you described it might be better idea to use cookies in certain situation like "Saving information when you are logged in to access some functionalities". Regarding error and warnings; you may like to remove some session variables after you have displayed messages on dashboard page.
For "Saving information on category, so the correct tab and/or form is displayed after a redirection" you can consider using parameters in URL to show desired tabs instead of using session variable.
In case you plan to use session_write_close() then in that case you would need to do session_start if you need access to session in the same script a second time. Use of session_write_close() is only to resolve locking of session in case two scripts try to access same session at same time. So you may like to describe if it is the case with your application or not.
I have a PHP application custom_appli in /var/www/httpdocs.
Wordpress is installed on the same server in /var/www/httpdocs/new_cms/wordpress.
I need to retrieve user->ID using SESSION of custom_appli.
I have tried to insert :
require( './new_cms/wp-snapshots/wp-blog-header.php' );
global $user;
$user = wp_get_current_user();
echo "ID :".$user->ID;
writing wp-load instead of wp-blog-header doesn't change anything no matter whether I use include or require_once.
Could you please give me a link or advice on how to obtain user from SESSION?
Thanks in advance
Details and info are sparse, but here's how I would do it (I know about 5 methods, these are the least painful):
As mentioned, wp_get_current_user() gets you close, but that is generally only usable on the page for the user as in "on load" only. So from the WP served page you can get user ID (and all other info) and the session and have something that is usable. There are many ways to use that data to solve your problem, not really smooth all the time. Session data is etherial, beware.
Another way to go about it is to use wp-load.php and wrap it in middleware. this script bootstraps WP and allows queries and similar in the "bootstrapped" wordpress environment providing the applications internal API. I would consider adding wp-load to custom_appli "in the right way" and use that as middleware between the 2 applications. You will still need to identify the user as in many cases.
Without more information it is hard to guide you, but I can tell by your needs and the code already in the post that you are setting up for possible problems with dependencies, possible name-spacing collisions($user is something that could bite you as a global), and a myriad of other ways to loose time. If custom_appli needs a user ID, send it the user from WP on page load or similar.
When/why do you need that info? What is the flow?
You can also traverse a lot via session ID info too (depending on configuration).
FWIW I have passed user information successfully from 2 freestanding applications on different servers, it was very hard to do correctly, but it is possible.
Update after clarification
As mentioned "wordpress-user and cusstom-appli have same users" is possibly a replication of functionality, specifically running 2 tables(?) or logic. Just some feedback.
Basically you are wanting to hook the "logged in" status of a WP user. I see no mention of:
FK/relationships built on user (easy but a little more work)
ACL/permission based access on custom appl
No serializing of data or similar to the WP user (user in general)
Any of the above might have me change the solution. Here is a pretty clean prototype I wrote for you that is about 15 lines of code.
It follows some code from wp and essentially:
Makes sure PHP session is initialized via the theme functions.php
Uses the WP login (authentication) success to add a var to the session
On logout unsets the var (!IMPORTANT!)
Also makes sure the session is set when not logged in or the key is not present
Is easy to pick up outside of WP via session (custom_appl.php)
I tested this and it worked fine locally on one of my installs, I don't see any reason why it would give you problems. I would harden this a little more, but this is only a prototype showing how to use the key tools in PHP and WP.
wp_get_current_user() is a function in wp-includes/pluggable.php, which is loaded by wp-settings.php. I'm not sure how exactly WordPress bootstraps itself but I'd try to include wp-settings.php if anything.
I'm using a CMS-framework that initates session_start() upon page creation, however 90% of the site visitors are guests without the need for sessions, resulting in an awful lot of empty session-variables at server.
What's the best practice here? IF logged in, I need to know at an early level so I guess it means is both:
Postpone session_start() until it's actually needed
Keep the session_start() at an early stage, but make it conditional based on existance of cookie PHPSESS
Or is there a better fix, unknown to I?
Many large sites postpone the session initialization until it's actually needed, e.g. on cart pages and the user profile screen of each user.
In theory this isn't that complicated, if you were using a config file which would be required within all pages you could simply swap out a different config file for the pages that don't require any user recognition.
You're using a CMS-framework so perhaps you're somewhat limited within it. If you can differentiate the page creation process, using session_start(); in one case and not in the other, then this shouldn't be that big of a deal. Keeping the logged in users logged on once returned to the other area of the system (the index file etc) would not work though. Of course you could be using local_storage to aid you with that but relying on JavaScript only isn't very reliable.
The easiest way would probably be to spit the system into two areas, one which doesn't use any sessions (index, other information files, etc) so the process behind those page creations would be different, i.e. not using sessions.
Perhaps you could have a session class like mentioned but it would most likely conflict with other previously outputs causing the sessions to fail, but if you could flush the other output then this could possibly work, but it's kind of a hack in my opinion and it wouldn't really solve the previously mentioned problem.
Have you considered changing the lifetime of the sessions? The default setting is 24 minutes but would reducing it to 15 change anything? Is 24 minutes really that big of a deal for you? Maybe the settings in your environment make them be even longer. Are there other aspects of the system that might be the actual performance issue? Are you hosting the system yourself or do those empty sessions really not matter?
If you're expecting a lot of guest traffic without the need for sessions, then don't use it unless you absolutely need it. What I typically do is create a class for session, and add the session_start to the constructor of the class. Then, when I need sessions, I can simply call the session class within an underlying global.class.
So as a engineer, I usually require a concert understanding to be able to work with something. I feel like I understand the basics of a session. I am wondering about the specifics and details there of.
What are the limitations of a session?
How can I manipulate a session? What can explicitly not be done to or with a session.
What data structures does PHP use to define and manage sessions?
Is a PHP session different from any other session in any significant way?
I understand that these questions are general, so if anyone can simply suggest a good resource I would be thankful. There is plenty of info out there, but it is either too basic or teaching to a specific topic.
Thank you for the help.
Sessions is a way for the server to recognize you so he sends to you a customized version of the page instead of sending always the same page for everybody.
To recognize you one way is he tells the browser to save in your computer a small file with a simple text, and when you visit the page again the server would ask the browser for that file, if the browser sends it, and it contains the expected content, the server can now know this is you again. That are cookies.
Another way to maintain a session, a part from cookies, is the server puts a special unique token for you in the url of all the links the page has. Whenever you browse the site all pages you visit will have that token, the server see it and know it's the token it made to you, so he knows it's you again.
So both with cookies or url-based sessions, the server will have to save info about the sessions opened, for example to store the $_SESSION variables you create in PHP, if you create such a variable the server will save it to a file which he will later identified by your cookie or token content and when you re-visit the page he will read that file and load the $_SESSION variables you create last time.
Here's a good resource: http://php.net/manual/en/book.session.php
What are the limitations of a session?
I don't really know what you mean by that. Limitations in what context?
How can I manipulate a session?
To manipulate values, just use the $_SESSION superglobal directly.
What can explicitly not be done to or with a session?
Again, without context, it's hard to understand what you mean. I guess an important point is that sessions are transient, so you can't explicitly store data you want to keep indefinitely.
What data structures does PHP use to define and manage sessions?
The filesystem.
Is a PHP session different from any other session in any significant way?
What is another session?
http://php.net is the best source for your questions
PHP session is a very nice way of having persistent information on your site for different users.
Check out the PHP session functions you can use.
You can view examples of how to use sessions at php.net.
A session is most commonly associated with user accounts. A user can log into your site, and you create a user session to keep track of their information and make sure they are allowed to be logged in.
The basic assumption is that a session is secure, because the server is aware of the sessions in progress. Utilizing sessions over HTTPS is a fairly secure way of keeping users logged into your site (without HTTPS you run the risk of session hijacking).
The other basic function is to have persistent data about a given user. So let's say you wanted to keep track if the user has submitted a form, you could do:
$_SESSION['form_submitted'] = TRUE;
And now you can check that global variable whenever you want to know if that specific user has submitted the form. So the session (in the same way a cookie is used) allows you to do really cool things that otherwise would not be possible.
This may be a bit of daft question, but I don't come from an OOP background and although I'm reading and learning as I go I'm still struggling with a few concepts.
Right now I'm working with PHP 5.3 and desiging a fairly simple login using a few different object classes: User which defines the user. Session which starts and maintains session data and if someone is logged in, and Database which does the queries.
So when my script is run, my session object is instantiated, etc... here's my problem though. When I move from one page to the next how is that object tracked? Or perhaps rather my question is how does PHP know the objects that relate to my login are mine and not someone else who logged into the site?
I know if I'm doing this in a non OOP way, I'd simply check the session cookie on each page and check my data that way, which is fine my brain can handle that. But, where and how is object data tracked.
EG:
On each page I want to check if someone is logged in I reference $session->is_logged_in() etc is_logged_in checks the a private variable name is true or false.
There's no checking of cookies at this point which means this object still exists, and, as it keeps asking for a stored variable the instance must persist to be useful... but how does PHP, the server, whatever tie that instance of that object to that user? If all of these objects float around on the server till I destroy them won't there be lots of memory used by objects?
As I said at the start it's probably a really basic, fundatmental question but I'm yet to have my eureka moment with this, I might go back to simpler PHP.
Session data (that is all the data in $_SESSION) is by default serialized and stored to file between requests. The data gets unserialized automatically when session_start() is called.
From the PHP manual on Session Handling (emphasis mine):
The session support allows you to register arbitrary numbers of variables to be preserved across requests. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.
Nothing is persisted in memory between requests. PHP has a shared nothing architecture, meaning all objects are recreated on each request anew, unless you are using dedicated cache mechanisms.
So when my script is run, my session object is instantiated, etc... here's my problem
though. When I move from one page to the next how is that object tracked? Or perhaps rather
my question is how does PHP know the objects that relate to my login are mine and not
someone else who logged into the site?
When you start a session, an id is generated. All the session data is associated with that id and it is given to the browser to store in a cookie. Subsequent requests include that id in the cookie, and PHP pulls the data out from where it has stored it.
If all of these objects float around on the server till I destroy them won't there be lots of memory used by objects?
The objects are serialized to files rather than being held in RAM, and are cleaned up with the session expires.
I find that sometimes, when I start to lose perspective as to whats really "happening", a quick trip to a page with phpinfo();,or just logging some ENV variables often clears things up, and puts me back on track…
Globals let you see exactly what "exists" in your environment, and allow you to take a mental restocking of what you're "working with", and how to best attack the challenge.. You'll find a wealth of information, and as to your specific "issues" there are such entries as…
$_SERVER["HTTP_COOKIE"]
$_SERVER["QUERY_STRING"]
$_SERVER["argv | c"]
$include_path
etc…
also, it never hurts to read through your /etc/php.ini (wherever the case may be) for a little one-on-one-time with PHP's internals - to remind you "what its all about".