Page load time with Cookie vs Session in PHP - php

I have a social network type site (member site) I store a lot of user data like username, userID number, email, first name, photo URL, into a user session when the user logs in to cut down on the ammount of DB queries per page. I sometimes hear people talk about using cookies for some things, I realize cookies should never be used for username/passwords but mu main question is, does a cookie slow down the page loading time? On a user's homepage I have blocks that a user can drag and drop to re-arrange there homepage, my first version I stored the location of the blocks in a cookie, I now store this value in mysql and I build the locations of the block in php on page load instead of using javascript to set the initial locations. When I first used cookies to set there locations though the page would load and the blocks would be in there original location, the page would then really fast change the location of these blocks from the value it got from the cookie, however this was much much slower and made the page seem really slow to load. I have always thought cookies were slow since then but maybe it wasn't the cookie that slowed it down.
So do cookies slow a page down?

A cookie is just an extra HTTP header with key/value pairs. Parsing that header and filling the $_COOKIE array does not add significant overhead (it's almost certainly not going to be a bottleneck).
If you're storing a lot of data in the cookie (i.e., not just a session id),then it's worth remembering that this data gets sent with every request to your domain, not just for PHP pages but for images, CSS, JS etc. For this reason, in a high traffic site you might arrange for these "static" elements to be served from a different domain to lessen the effect of this overhead.
If that cookie value is a session identifier, then PHP needs to retrieve that session, either from the filesystem, database or other storage mechanism to populate the $_SESSION array. This can take add a little time, but it really depends on the mechanism used.

If I understand correctly, you are saying your page was slow when :
the positions of the blocks were stored in cookies
and the blocks were positionned in Javascript on page load
I think the "slow" part doesn't come from the cookies :
those are quite small, compared to the size of the page
yes, it adds some overhead, but not that important for a single page
it becomes more important if you have lots of assets (images, static files, ...), as they are sent with each request, though
they don't contain much data
But, with that solution, what could cause an impression of slowness is that :
the page is loaded with block at their default positions
some JS code is executed to re-position the blocks
which means waiting a bit before blocks are re-positionned
which takes some processing time to execute the JS code
which also means, for the browser, re-drawing the page several times (each time something changes).
IMHO, what makes your page "faster" now is that the client receives the whole page with blocks already well positionned -- which means no processing at all on page load :-)
The smaller/absent cookies might make a small difference... but small.
If you want to read more about cookies size and their impact on load-times, and some recommandations, you can read this article from Yahoo : Performance Research, Part 3: When the Cookie Crumbles ; it's a pretty interesting read, and not too hard to understand.

Cookies will slightly increase the load time for your pages, as the cookie data has to be sent with each request.
For the HTML page, this won't make much difference, but if you have all your assets on the same domain (as is usual) it can add up to a significant difference.
Actually reading the cookie in PHP should not take a noticeable amount of time.

Related

Passing class Instances and other data between pages in PHP

I've been looking into the problems of having persistent data available between pages in PHP. This particularly applies to objects that have been set up in one page that need to be accessed later. It seems this is more difficult than I assumed it would be, but there are several ways this could be done, although they all seem a bit awkward to use especially when the data gets quite complex:
Passing the data via $_GET or $_POST to the next page
Copying the data to a database and retrieving it in the next page
Putting the data in a session or cookie
Serializing the object and recreating it with the same parameters and values
These all seem quite laborious as they mostly rely on having to deconstruct your existing data structure and then rebuild it again on the next page. I assume this is to reduce memory requirements of the PHP server by purging data from one page as soon as its closed and starting with a 'clean slate'.
Is there a more direct way of passing larger data structures between pages in PHP?
Many thanks,
Kw
I assume this is to reduce memory requirements of the PHP server by purging data from one page as soon as its closed
Nope, this is not because of memory efficiency concern. This is because HTTP protocol is stateless. Each request must carry all information that is necessary to fulfill it.
Counter-example to your proposed scenario:
let's suppose Alice visits page A, some objects are created and you want them to be available in page B.
You track a visit to page B.
2.1. But it's not Alice, it's Bob. How do you determine which objects to show and where do you get them from?
2.2. It is Alice again, but the request arrived to another machine from your 1000 server farm. Naturally, you don't have original PHP objects. What do you do now?
If you use $_GET or $_POST you are limited to non-sensitive data and you expose your objects to any user. You don't want that.
Cookies are limited in size
cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site.
The best way to persist objects between requests (for the same user) is to use Sessions. There are already session save handlers for memcached, redis, mysql etc. You can also write your own if you need something custom.

large select slowing down page load - caching php

I'm building a web app, the way I started off the app for testing purposes is to load lots of data in to session arrays from my database so I can use the values easily throughout the pages. I have one page the has numerous selects on it, and each time the php page loops through all the variables, chooses the selected one, and outputs the dropdown. One of my arrays though has just under 3000 values and loading this dropdown slows the page down from about 300ms to 1-1.2s. Not terrible but easy to tell that it is less responsive. So I'd like to know if there is anyway for me to improve the load speed, or any thoughts on a substitute for the dropdown.
What I have tried so far:
Session arrays hold all the values, when the page is loaded through jquery ajax method the php page loops through these values and echos the dropdowns.
Php include - create php or html pages of all the values pre written as selects, this creates a ~100kb page for the problem dropdown and this is then included with include. Takes roughly the same amount plus I'd have to then use javascript to set the value, but I'd do this if it could be improved. I thought perhaps some caching could provide improvements here. There seemed to be no significant difference between html and php pages for include but I'd assume html would be better. I'm also assuming that I cannot use regular caching because I am using a php function to include these pages.
I have tried just loading in the html page and it takes about 1 sec on first load, after browser caching it is back down to 100-350ms so I imagine caching could provide a huge boost in performance.
I have considered:
Creating a cached version of the whole page but this will be quite the pain to implement so I'd only do it if people thought it is the right way to go with this. I would have to use ajax to retrieve some data for the inputs which I was originally doing with php echos.
Just removing the problem dropdown.
Just to clarify something I've never had clarified, am I correct in thinking php pages can never be cached by the browser, and so by extension any php included files can't be either. But then how come a javascript file linked to in a php file can be cached, because it is using an html method?
The data being returned and parsed into a dropdown is probably your bottleneck. However, if the bottleneck is actually the PHP code you could try installing an optcode cache like APC at http://php.net/manual/en/book.apc.php. It will speed up your PHP. (Zend Optimizer is also available at: http://www.zend.com/en/products/guard/runtime-decoders)
If your bottleneck is the database where the items in the dropdown is coming from, you may want to try setting MySQL to cache the results.
You may also want to try an alternative dropdown that uses AJAX to populate the dropdown as the user scrolls down, a few records at a time. You could also create it as a text field that prompts the user for possible matches as they type. These things may be faster.
I suspect the problem is the raw size of the data you're transmitting, based on the results of number 2 in "What I have tried so far." I don't think you can rely on browser caching, and server-side caching won't change the size of the data transmitted.
Here are a couple of ideas to reduce the amount of data transmitted during page load:
Load the select box separately, after the main page has been
delivered, using an asynchronous javascript call.
Break the choice into a hierarchical series of choices. User
chooses the top-level category, then another select box is populated
with matching sub-categories. When they choose a sub-category, the
third box fills with the actual options in that sub-category. Something like
this.
Of course, this only works if those 2nd and 3rd controls are filled-in using an async
javascript call.
Either way, make sure gzip compression is enabled on your server.
Edit: More on browser caching
The browser caches individual files, and you typically don't ask it to cache PHP pages because they may be different next time. (Individual php includes are invisible to the browser, because PHP combines their contents into the HTML stream.) If you use a browser's developer console (hit f12 on Chrome and go to Network, for example), you can see that most pages cause multiple requests from the browser to the server, and you may even see that some of those files (js, css, images) are coming from the cache.
What the browser caches and for how long is controlled by various HTTP response headers, like Cache-Control and Expires. If you don't override these in php by calling the header function, they are controlled by the web server (Apache) configuration.

Is it good to cache page with cookies?

I use cookies for page cache, is that okay?
To show partially static contents( updated very rarely from database),
i don't like to interact much with database so can i use cookie to store that results in client's computer and display data directly from it?
For data authenticity and integrity, i created a crc for data and stored along with data in that cookie.
THe algorithm of crc calculation is hardcoded(assume), so
Does the idea has any demerits?
Cookies should not be used for caching, since your cookie is sent from the browser to the server on each request!! This means you send more bytes, which means higher latency. So you are actually slowing your system down, not helping it, by using cookies in this way. The proper way to cache data on a website is to use localStorage (or one of the other HTML5 storage classes) to cache it.
This sounds like a bad idea to me. Is the cached data user-specific or global? For global data you'd be much better off caching the entire generated page on the server side and responding with that for future requests. Using cookies you'd still need to dynamically generate a page on each request.
For user-specific data, it depends on the page, but you generally want to store thing like a user's name in the session. Caching something like a user's profile page won't be very helpful since it doesn't get hit very often.
In either case, you're going to end up wasting a lot of bandwidth receiving all that extra information on each request and you still have to dynamically generate a page for every request. There are also security implications if your checksum algorithm is compromised and you store anything important in the cookie like an account balance or even a username. Further, how do you invalidate the data cached in the cookie? There would need to be a mechanism on every request to check if the data is old, which defeats the purpose.
Cookies should be used to store small strings like session ids and usernames.
You're better off writing the static content to a local file on your server (or to a database) and serving the static content until you decide to expire it - then repeating that process.
There are servers, such as memcached, which are very efficient at doing this but the psuedocode is the same:
if (is_cached('recent_articles') {
return cached_content('recent_articles');
else {
save('recent_articles', $articles)
return cached_content('recent_articles')
}
Just make sure to expire content after a certain amount of time or when you know its stale - whichever makes the most sense.

Am doing online Quiz type of script in PHP. It is better to use cookies or sessions

Am doing online Quiz type of script in PHP. User needs to attend 50 Question in 45 minutes.
After that time it should close the page or Submit the answer to the next page.
It is better to use cookies or sessions. How can i do that.
Am novice in session concept so can u suggest the suitable code.
Awaiting the earliest reply
I assume, as this is a quizz, you'll count point, record ranks, etc. So your users will eventually try to cheat.
Therefor, I would recommend sessions which are only server-side.$_SESSION is an array, like $_GET and $_POST, unique to every user using your website. You can put and retrieve anything when you want.
The only thing client side is a special cookie, called PHPSESSID, which is your visitor's id, used by PHP to retrieve his $_SESSIONarray.
Only things you have to do is to begin every page with session_start(); , before any instructions (except if you use buffering like ob_start())
The main difference between cookies and sessions is where the data is stored.
With cookies, you send the data to the browser, and the browser keeps sending it back to you with every request thereafter.
With sessions, you're storing the data in memory, and then just setting one cookie that has an ID to identify the chunk of space in the server's memory where the data is stored.
The crucial difference is that when the data is stored in cookies:
it can be edited by the user
it can be seen on the network as requests are made
it adds to the weight of each request in additional bandwidth required
it takes up less server memory
When data is stored in the session:
it can't be accessed by the user without going through you
it's not sent back and forth with each request (only the session ID cookie is)
but it takes up memory on the server
it can cause issues on larger sites when needing to move to multiple web servers
I would say it depends on scale. For a lot of questions, those cookies will get heavy and make each request very large. If you quiz is running in an environment that is spread across multiple front-end web servers, sessions might be out of the question.
I suspect the deciding factor is going to be the integrity of the quiz though. If it's crucial that the user can't change the data (such as previous answers, a running score or a timestamp for the start of the quiz) then you'll need to store the data out of their reach, which means using sessions.

Caching variables in the $_SESSION variable?

I'm making a php web application which stores user specific information that is not shared with other users.
Would it be a good idea to store some of this information in the $_SESSION variable for caching? For example: cache a list of categories the user has created for their account.
This would be an appropriate use of the session mechanism as long as you keep this in mind:
Session does not persist for an indefinite amount of time.
When pulling from session, ensure you actually got a result (ASP.NET will return NULL if the Session has expired/cleared)
Server restarts may wipe the session cache.
Do this for convenience, not performance. For high-performance caching, choose an appropriate mechanism (i.e. memcached)
A good usage pattern would be like this (ether cookies or session):
User logs in
Store preferences (background color, last 10 records looked at, categories) in session/cookie.
On rendering of a page, refer to the Session/Cookie values (ensuring they are valid values and not null).
Things not to do in a cookie
Don't store anything sensitive (use session).
A cookie value should not grant/deny you access to anything (use session).
Trap errors, assume flags and strings may not be what you expect, may be missing, may be changed in transit.
I'm sure there is other things to consider too, but this is just off the top of my head here.
That could work well for relatively small amounts of data but you'll have to take some things into consideration:
$_SESSION is stored somewhere between requests, file on disk or database or something else depending on what you choose to use (default to file)
$_SESSION is local to a single user on a single machine.
sessions have a TTL (time to live), they dissapear after a set amount of time (which you control)
Under certain circumstances, sessions can block (rarely an issue, but i've run into it streaming flash)
If the data you mean to cache is to be accessed by multiple users you're quickly better off caching it seperately.
If you only want this data available during their session, then yes. If you want it available tomorrow, or 4 hours from now, you need to save it to a database.
Technically you can modify the sessions to have a very long lifespan, but realize if they use a different computer, a different browser or flush their cookies they will loose the link to their session, therefore anything serious you should create a type of user account in your application, link the session to their account and save the data in a permeate place.

Categories