Note: Now that I know where the issue comes from, I modified the question. It now contains only the information needed.
I'm new to the Laravel PHP framework.
I have a very small app working on my computer. It is connected to a MySQL database and has a User model. I use the Auth class to log in and out.
Everything works fine, but when I am logged in, loading a page takes about a second which is very slow. When I'm not logged in, it's a matter of milliseconds.
By using the built-in profiler, I realized two problems. First, like I said, loading a page takes a bit more than 1000 milliseconds. Second, the framework makes one SQL every time I load a page when I'm logged in. The query searches a user with a certain id (my id). I guess it is there to get information about the logged in user. But isn't there supposed to be some sort of cache. Will this be a problem if my website will have to manage many requests per seconds.
I realized that using Auth::check() in the view is what is causing the issue. I have around 4 Auth::check() is my Blade view. When I have none, it goes fast. If I have one, it is slow. Then, no matter how many I have, it doesn't get much slower. It's like if the Auth class' initialization takes too much time or something like that. I guess it explains why it only happens when I'm logged in.
I dived into Laravel's code and I found out that when Auth::check() is called for the first time, the Auth class needs to "activate" my Session by retrieving the user's info from the database. That explains the query being executed every page request. But since the profiler says that the query doesn't even take a millisecond to execute, I still don't know why it slows down the app.
New information: Even when I'm not sending a query to the database, the simple act of connecting to it takes almost a second. This is the reason it is slow. I think I'm getting really close to solve the issue.
Any idea so far?
Thanks in advance.
Notes
The fact that Auth::check() is in the view doesn't change anything.
Using another method like Auth::guest() doesn't solve the issue.
New: Connecting to the database is what is slow.
I finally found a way to fix this.
When reading some posts on many forums about XAMPP, MySQL, and PHP, and I read somewhere that it is preferable to use 127.0.0.1 because locahost needs an extra DNS lookup.
In the database configuration file, I simply changed locahost for 127.0.0.1.
Now everything is fast.
I find this really strange. Using locahost in the configuration file used to make the database connection take more than a second!
I do not agree with Hammo's example. Having any user information other than their ID within the session is a security risk, which is why most frameworks take this route. Is there anything else being run when the user is logged in, apart from the query for their record? It's definitely not that that's slowing your application down.
Related
Here is the problem we have been facing for the past few weeks.
1/ Our setup
PHP 5.4 + MySQL
2 dedicated servers, load-balanced
Sessions are replicated between the 2 servers using memcached
3 applications running on these servers :
One custom-developped application, using default php session settings
Another custom-developped application, using different session settings (cookie name, path)
One Wordpress CMS
2/ The problem
The problem occurs on our first application.
Some of our users reported that they sometimes get disconnected after a few minutes (when the session is setup to last 3 hours). It can happen to them several time in the same day, then no disconnection for a few days, but the problem always comes back.
So far the fraction of users impacted is small, but I would like to solve this before it "spreads" to other users.
The problem seems to occur in different places of the application, though we have identified 3 scenarii where most of the errors occur :
Some involve submitting a form ($_SESSION variable is modified)
Other simply involve opening a popup page, with no modification of the session data
We have tried to reproduce the different scenarii described by the users : sometimes we have been able to, but most of the time we don't have any problem, which makes it hard to debug.
Other notes :
The problem is recent, this application had been running for years without any problem.
It doesn't seem to be related to our server load, because the problem still occured during the summer break when our trafic was low
It only affects one session/users at a time: all the other users logged in at the same time don't experience this problem
The problem occured on all the different browsers (IE, Firefox, Chrome)
3/ Technical analysis
When a disconnect occurs, the user is redirected to a page "Your session has expired or you don't have the right to view". When this page is loaded, we get a technical email with a dump of the $_SESSION variable.
When a session expires the normal way, the email we get shows that the $_SESSION variable is empty (normal behavior).
When an unexpected disconnect occurs, what is interesting is that the $_SESSION is not entirely empty : out of the ~20 elements the array contained, only one is left (always the same).
So this would mean the session is not expired, but not enough data is left to "identify" the user, hence the "no rights" page displayed. As a confirmation when this occurs, we can check in memcached that this session still holds some data.
These are the potential problem causes we have identified so far, and what we have done to rule them out :
Memcached indicates between 70 et 80% freespace, so we don't think it is the problem.
We removed Memcached and went back to using a NFS shared directory for session files: the problem actually got worse. This would point to an applicative bug, because NFS being slower to write data, session loss would occur more often.
We have browsed all the different forums (including SO) talking about PHP session data loss, and reviewed our code accordingly. The code base is big, but we have used automated tools and scripts to avoid missing a file.
session_start() is called at the beginning of each page.
exit() is called after each header("Location...")
register_globals is Off
We have tested the possible interractions between our 2 other applications and the problematic one, though they don't share any code, database or session handling. Nothing identified there.
We have analyzed our access logs around the times of the disconnections, to check for behavior patterns : no luck here either.
So we have no idea what causes this problem, as it seems to occur randomly, so my questions are :
The problem could come from our code: did we miss anything to check ? This solutions seems unlikely as the code works most of the time for all our users, but I am still considering it.
The problem could come from another application/process that would "empty" part of the session variable array. We have also reviewed the code from the other applications, but didn't find anything that could cause this.
And if another process is doing this, why would it only empty some sessions and not all of them ?
Thanks for your help.
I don't think you'll get a definitive answer to your question. There are too many probable causes and you haven't shown any code.
Still, my guess is that you have memcached.sess_locking turned Off, or if you have a custom session implementation - that it doesn't implement locking at all.
Eventually, this leads to a race condition between two simultaneous HTTP requests.
My guess is based on the often seen bad advice to turn off locks or free them as soon as possible, in order to achieve higher performance.
If this problem "suddenly" occurred, check what has changed. Did you do any work on the application? If so check committed code (you talked about automated tools so I expect there to be a repository which would allow for accurate finding of code changes).
Did you change anything on the server? Like upgrade software, upgrade/change hardware, make changes to the other two applications ?
One thing that popped to mind, did you check the drives you use for caching? It could be a corrupted part of the file system. Which would explain the random user part.
I couple of things I always to is:
Try to determine the moment of first occurrence as accurate as possible. At my work this occasionally triggers someone saying "oh yeah that might have to do with when I changed/updated/created this or that" so this might help. On the other hand it can sometimes takes days, weeks or more before something gets noticed so start expanding that time-frame if nothing comes up.
You have already a couple of scenario, find the common factor in these. If they don't share any code, stop looking there. If they DO share code search there. Of course sharing (part of) it here might allow us to help you search.
Do an organised search. I usually do the main application check when I am the one working most on the application (or even better when I created it). A colleague will check surrounding applications that might have influence on it. In your case those 2 other applications. Finally our sysadmin will check for newly installed or updated software on the server(s) and he will also check with our network guys if anything changed hardware wise or network related (for other people this could be the hosting provider).
It could be as simple as a WordPress plugin that uses sessions and calls either session_name() or session_id() with a different value, overlapping your custom applications with default session settings.
Since WordPress itself does not use sessions, plugins are often written from the perspective of having free rein with sessions. I just did a search on a WordPress test site and found sessions used in a gallery plugin, a plugin for putting a background image on the page, a shopping cart plugin, and a plugin I was writing that needed to carry an uploaded file from one admin page to another.
I'm a little beginner to PHP and currently doing a project work that involves the task of displaying sessions that are currently live. But, I read in the documentation that sessions were stored in tmp folder and will be automatically expired when the browsing session ends. So, what can I do — I also googled and found that it can be stored in Databases and then we can get the count?
Was that possible? If so, please give me the methods for that.
Update: Also, please give the way such that entry in the database must be automatically removed when the session ends
I would suggest you define / let your stakeholders define what information you are after. If it is the technical webserver-number of current active sessions than you can keep on looking at what you are doing, but if you are looking for "number of users on the site" for instance, you should step away from the PHP-concept of sessions. They are something else.
Instead, as saving all this can be somewhat tricky, take a look at the "realtime" functionality on google analytics, maybe that'll be enough.
If that isn't, you need to make a database, register each load and update the loading-time on each action, so you can check out if someone was active during a certain period
I wonder if the following would be a good Idea or rather contra-productive performance-wise:
An Ajax-Application, like for example a pagebrowser needs some language- and config-values, which are stored in the database. So each time, the user is using this app, in the ajax-script the mysql-query to get the variables is done again and again. concidering this for a pagebrowser, there might be like 10 or more requests (back and forward, back, forward, and so on), aka 10 x database-select, while it is needed only one time actually.
My idea was, to safe the config-vars in a session-array the first time, the ajax-app is requested. If the sessions-array exists, the mysql-query isnt done again.
if the user calls another regular page, these session-array is deleted again.
Now im not really sure, what would consume more server-resources, using sessions in the above described way for saving the vars teporarily, or just using a mysql-query to get the vars each time, the user klicks the ajax-app.
Thanx in advance, Jayden
If you working with massive amount of data, you could consider using Cookies as well instead of session for server resources, which will be stored in the user's local browser.
I'd bet sessions would be more effective, but the best way is to test and measure the different execution times.
I'm currently building a web application that uses a combination of OpenID and uname/pw authentication to authenticate users. Users are supplied a PHP session when they login successfully, and some information about their account (email address, usergroup, blah blah) is written to that session.
However, there may be a need for me or someone else as an administrator to update a users details (or to ban them immediately if they're very naughty). I'm hesitant to use a killsession tag like this (pseudocode):
session_start();
mysql_start(connection_stuff);
if (mysql_query("SELECT FROM users WHERE uid = '$_SESSION['uid']' AND KillSession = true")) { Kill session, force reauthentication };
However, doing it like this has two flaws:
We have to query the database every time someone loads a page to see if something changed
We gotta log the user out which just annoys him (or reload all of his session variables, which doesn't seem efficient)
Is there some way I can modify a user's session while they're still in it without having to resort to forcing them to login again? Some people seem to suggest in this stackoverflow thread using session_id to change to the user and then fiddle with their variables, but that seems like a shoehorn way of doing it. Thanks in advance!
I think instead of storing that stuff along with the session, it should be kept (and cached) separately. That way you avoid data duplication and the issue you're running into right now.
If an admin needs to kill the session, just DELETE it from the table.
Even though you express concerns about having to query the database on every page load, my guess is that it most likely does not affect performance noticeably. If the website is database driven in the first place, them it's just a matter of a single more query. I'd actually say that moving the entire session handling to the database (store session variables in a table) can make your system better in terms on flexibility. It will be much easier to deploy your system on multiple servers and do proper load balancing if that is someting you think will become necessary at son point. That is how the bigger CMS systems handle their sessions. My advise is, in other words, to stick with the extra query and actually consider to move session state to the database.
I have found what looks like a good, secure PHP login script, however i am having trouble figuring out how to implement it. (It is located here http://www.adesdesign.net/php/tutorials/php/php_login1.php)
I am new to PHP so don't know much yet. I can't figure out how you actually authenticate a user and return a message to them if it fails and where to stick all the functions and classes mentioned throughout.
I know it may be very obvious to some but i just don't get it!
Thanks.
Not the easiest script/way to do it, but quite complete. You say you're new to php, what about OOP ?
IMO, this one seems easier : tutoriel.
Principle always stays the same : you have in your database a table with your user.
The visitor come and try to log.
If his login/password are good, you redirect him to his profil/any page you want and you store in $_SESSION['verifiedUser'] = true ,
if his login/pass are wrong, he's redirected to the login page, with an error message.
And in every page restricted to logged user, you add
if (!isset[$_SESSION['verifiedUser']) )
header('Location:loggingForm.php');
Clement answer is perfect.
May be the pear Auth class can be usefull
Just a note because you siad your are new to php: the authetication process is not the only important thing. You should also think about the ACL (access control list), a mechanism which allows an authenticated user to do some things but not others on one or more pages
--
Dam