PHP - Using Sessions to temporarily save variables for ajax application - php

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.

Related

Maintaining State Between HTML page and PHP Server Page

I am designing a simple drag and drop quiz. We are limiting the number of attempts to get a correct answer to two for each box/answer. However, I'd like to keep the functionality and state of the quiz separate from the display/view.
Currently, as the user attempts to get a correct answer by dropping an answer box on top of a question box, an ajax call is made to a PHP page which returns a 'true' or 'false' value.
We have been evaluating if we want to use Session variables on the PHP page, cookies, or something even more simple to track how many attempts each box has consumed. It would be preferable (for good form's sake) to somehow maintain the state of this data on the server - so the client has no idea what is going on. Session variables seemed to make sense to me - as the user continues to make attempts with different question/answer combos, the server tracks the number of tries and returns (in the ajax response) the result of a user's question (right/wrong, and how many tries that answer has remaining, if any) but I'm wondering if there's a better solution. Any input?
Session seems like a good fit to me. Cookies can be tampered with so I would avoid that if you need the error count to be accurate.
Sessions is probably your best bet. Cookies could be used as well, or if you can guarantee availability of HTML5 localStorage in the browser, you could use that as well.
Unfortunately to keep the functionality separate, there is not. You can use a session variable, or database storage paired with a session id stored in a cookie.
Store current user state into session (temporary storage) and track what he have answered what not etc. at the last step store data into database, or file (permanent storage). Session is individual for every user. Users can't alter your site sessions.
Session usage

Best practice for storing global data in PHP?

I'm running a web application that allows a user to log in. The user can add/remove content to his/her 'library' which is displayed on a page called "library.php". Instead of querying the database for the contents of the users library everytime they load "library.php", I want to store it globally for PHP when the user logs in, so that the query is only run once. Is there a best practice for doing this? fx. storing their library in an array in a session?
Thanks for your time
If you store each user's library in a $_SESSION as an array, as you suggested (which is definitely possible) you will have to make sure that any updates the user makes to the library are instantly reflected to that session variable.
Honestly, unless there is some seriously heavy querying going on to fetch a library, or you have tons of traffic, I would just stick to 'execute query whenever the user hits library.php'.
Consider the size of the data. Multiply that by the maximum number of concurrent users.
Then compare that the to memory avaiable on your server. Also consider whether or not this is a shared server; other sites needs resources too.
Based on this, it is probably best to either create a file that can be used (as per Remi's comment), or remain in the default stateless form and read every time. I doubt that reading the data each time is creating much of an overhead.
When the user login you can generate a xml file (USER_ID.xml for instance) that you display with xslt.
http://php.net/manual/en/book.xslt.php
Each PHP script dies when it completes, so data can not be kept permanentely live in a web application as you would do in a PC application.
One way could be sessions, but it depends on the amount of data you want to save. According to your example you are talking about a library, so it sounds to me like big quantity of data need to be saved, in such case the DB is the way to go, and yes you have to query it each time.
Another way could be to save them in an array inside a php file, but in the same way you have to query the DB each time, you would have to include such php file each time.
Since this is a db performance optimization, I would suggest that you take a look at memcached which matches your problem perfectly:
memcached is [..] intended for use in speeding
up dynamic web applications by
alleviating database load.
I think it would be best to store it in a Session.
It the user logs in, the Session is being created and you can save data in it using the superglobal:
$_SESSION['key'] = "value";
You can also store Arrays or everything else there and it can be cleared if the user logs out.
you care for performance; Please note:
Session may use database or file to store data.
database is here to be used instead of files, for it's performance and abilities.
use database, it is designed to be used exactly in such situations!

how do php share data without access a DB

I have two pages and I want to pass data to each other.
How can I do this without accessing a DB?
Sessions? Cookies? someother magical way?
If you know how, can you please post sample code?
Thanks
Session variables is one way:
$_SESSION["variable"] = "value";
This variable can then be read/modified by another page.
Also note, that you need to start the session by calling start_session(); at the beginning of your script.
And Cookies are another way... You can also try writing in and out of a file instead of a DB
How does a user get between these two pages? I assume a Form based solution is out of the question...
Amongst the possibilities, here are some that I think about :
You could $_SESSION (see Session Handling) -- if both pages are accessed by the same user, without too much time between the two accesses, so the session doesn't expire.
You could store your data to a file ; that'll work fine if :
The amount of data is big
You want it to persist for a long time
But you'll have to do some cleaning-up by yourself
Another idea would be some external daemon, like memcached
But, as it's a caching engine, it's not necessarily good for storing data : the data that is cache can be removed from the cache even if it has not expired yet (i.e. if there is no place left in cache, memcached will remove some least used data)
Of course, if the data is small and you don't mind it going back and forth through the network, and both pages are accessed by the same user using the same browser, you could use cookies
Only a couple of possibilities, though ; my preferences would probably be :
$_SESSION
or files
Depending on your situation.

Save to session - Does a cache mean the back end code doesn't always run?

So for a bit of background, I am creating a website with the Zend Framework. There is a page where I am using AJAX to save a rating to my database. I obvious need the key for the store in order to know what store the rating is to be saved for.
In order to access the store for the page, the URL is MYSTORE.com/stores/2. The 2 is the store key, so it could be 13, 10, whatever. What my PHP script currently does is when it loads the page, it stores the store_id as a session. Then if they rate the store (all in JS), it will snag the store_id value from session, and combine them to send an insert to my database. So here's my problem.
Somewhere down the line, I'll probably want to cache to save my server some trouble. I have never used one before, and am worried that instead of running the script that saves the store_id to session, the page loads from the cache and never stores store_id. This would mean that the review could theoretically be saved to the wrong store. Is this a reasonable worry, and is there a way around this?
My other question is if there was maybe a better way to do it. I'm hesitant to place the store id into the JS or HTML since (at least I think) you can mess with the scripts through Firebug, or other web tools. I'd like my page to be secure. Is there a better way to do this?
I hope my question makes sense, and thank you in advance.
-Ethan
My advice is don't solve a problem until you have a problem. When they load the page just put the movie ID in the URL, possibly with some sort of checksum or hash so someone can't just blanket upvote and downvote every ID.
There's no need to store this in the session. Just keep it in the database until you need to change it. Don't forget that sessions are file-based. Using them for performance gains is a little misguided. Just use them where appropriate.
Knuth said "premature optimization is the root of all evil" and that's what this looks like to me. You're right in that you greatly complicate your code by keeping an ID in the session and that can get out of sync with what the user is seeing (eg using the back button). Stick the ID in the Webpage and that problem is solved.

Can you put too much information into a variable?

I'm creating a script that makes use of the $GLOBALS variable quite a lot. Is there too much you can put into a variable?
If I have a lot of information stored in $GLOBAL variable when the page loads, is this going to slow down the site much or not really?
Is there a limit to how much information one should store in a variable? How does it work?
And would it be better to remove information from that variable when I am done with it?
Thanks for your help! Want to make sure i get this right before I go any further.
In PHP, there's a memory_limit configuration directive (in php.ini) that you should be aware of.
As meder says, you should really be taking a step back and re-evaluating things. Do you actually use all of those data on each and every web server request.
In almost every case, you'd be better off loading only the data you need, when you need it.
For instance, even if you're reading all this data from some file, instead of a database, you're probably better off splitting that file up into logical groups, and loading the data you need (once!), just before using it (the first time).
Assuming you're running Apache/mod_php, loading everything on every request will balloon the size of your httpd processes, and when you scale with traffic, you'll just start swapping out (which means your app will slow to a crawl, or even worse, become deadlocked) that much faster.
I you really need all or most of the data available for all (or nearly all) requests, consider looking into something like memcache. You can devise ways to share (read-only) data between processes, instead of duplicating it for each and every request.
Some people use a "Registry" object to handle globals.
See how Kevin Waterson does it:
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html (See "5. The Registry")

Categories