how do php share data without access a DB - php

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.

Related

Passing data directly between different sessions. Possible?

Maybe stupid question but its still interesting for me. Is it possible to transfer some data between different sessions? Can I add some variable into another user's $_SESSION directly? Something like this abstract code:
$notMySession = getSessionById('123'); $notMySession['kindaInfo'] = 'something'
No directly you cannot transfer session data from one session to another session. That is what the session is made for.
I hope this helps you.
Each user has its own session, which PHP will use when it speaks to that specific user. That means that each session is isolated from one another.
Since the session is not stored on the users computer, there might be a way to reach the session files from your code and directly modify the files. But that doesn't sound like a particularly sane thing to do.

Is passing session data from one PHP page to another efficient?

I was wondering if using a SESSION variable to pass data from one PHP page to another is efficient. I ask this because I thought that SESSIONS were only used to keep the user logged in to a website, and as an alternative to cookies. Would it not be better to pass data (non-sensitive) from one page to another via a URI such as members.php?name=Joe&age=28?
A PHP session writes a cookie to your browser and then stores the data associated with that session on disk; its about as expensive as an include() to read it back in on the next page load, which is to say completely trivial.
Additionally, the user can't change session data unless you create a mechanism which allows them to; they can mess with the query string easily.
Short answer: Yes, its efficient.
Sessions are useful for lots of things, not just login information. They're great for holding status messages during a POST/redirect/GET cycle or anything else that keeps track of the state of the user's session (hence the name) - but only the current session, not long-term permanent configuration options.
As far as efficiency goes, you need to remember that anything in the session needs to be serialized & unserialized on every page load. Storing a name and age wouldn't add much. Adding a megabyte of image upload would probably be bad.
More important than the efficiency consideration is to remember that session data is only temporarily persistent. If you want to always know that Joe is 28, it should go in the database. If it's only useful on a single page load, it should probably stay in the URL or be POSTed. If you're interested in remembering it for a few minutes, the session might be the place to put it.
Depends on what you're doing. If that page requires that information to function properly and is not behind a login then passing in a query string is the way to go (e.g. search results, product pages). If it is behind a login then using a session would allow you to keep your URLs clean and also make it difficult for users to abuse the page (e.g. swap out data in the query string).
Yes, you can store data and message in SESSION and it is accessible from any page. But remember, SESSION uses browser support to store data. They can be deleted manually by the user

Storing large amounts of info within a cookie

I'm working on a demo tool (PHP, jQuery, XHTML), so far so well, except that I have an issue, I need to save certain information temporarily and I'm doing it through cookies, however the cookies' limit in Apache is 4Kb and I have no longer space within the cookie, so I'm wondering how can I keep saving inside the cookie without a problem if I still don't want to send any information to databases nor text files.
I don't know if maybe by using path or other domain I might be able to work things out.
I would really appreciate any help you can provide me :).
Sessions are like Cookies but they just give the client a unique ID ("session ID") and keep the rest of the data on the server.
Of course this is stored within a database or file but that's totally transparent to you, there's no messing about with SQL queries or file reads or anything.
You just need to replace all $_COOKIE with $_SESSION and put session_start(); at the top of your code: http://www.tizag.com/phpT/phpsessions.php
One downside though: PHP sets all session cookies with no timeout, which the browser usually treats as "delete this cookie whenever the browser is closed". See this question for workarounds: How do I expire a PHP session after 30 minutes?
First you should consider if saving that much data in a cookie is really needed. Maybe you can compress your information or just dont need all of it?
The reason is: the cookie is send at every request to the server (this might more then 1). If you serve images from the same domain, you may get over 20 requests each is sending this large cookie. Assuming your cookie holds 5kb of data, you have 100kb just to loop your information through.
see: http://developer.yahoo.com/performance/rules.html#cookie_size
if you need your information just for the current session, why not saving it into a session var (or memcache etc.pp.)?
Maybe its okay if you just save an id in the cookie and if nothing to this id is in your session, you load it from database and save it in the session. so you have a one-time access per session.
Maybe its better if you provide some more background information.
You could create multiple cookies, but it's a bad idea. The cookies will go across the wire with every request. Consider putting your session information in a database or cache tier.
I guess you could store non-sensitive information with a DOM element. If you are using jQuery you can use .data() - http://api.jquery.com/data/
However, after the page does a full reload its gone.

What's the best way to store temp data in PHP across page views?

What's the best way to store temp data in PHP across page views? MySQL or server side cookies? Or something else I don't know about?
You could use the $_SESSION variable. I've seen people using it to keep session information such as cart contents, and generally to pass information from one page to another.
There's an extensive documentation on session variables at http://www.php.net/manual/en/ref.session.php .
I would advise against MySql in this case.
I prefer using PHP session for storing data on server side. For efficiency you can use memcached to save session values (default are saved on filesystem).
You can use $_SESSION like Clement suggested, but $_COOKIE may be appropriate also. Especially if you need to fetch the values client side. Here are some examples on how to use Cookies in PHP: http://www.w3schools.com/php/php_cookies.asp
Session variable is backed by a storage mechanism, that is, when the request finishes the session gets written by the session handler, by default this is to a file. On the next request it is pulled back from that file (or whatever else the session handler uses).
If you're reading and writing this data on every request, just stick with a the $_SESSION variables, the overhead of connecting, querying and updating a database will not be faster than the default $_SESSION.
You'll probably only ever want to use a database backed session if you are running multiple load-balanced servers and need to share the session data between them. In this case, if you find the overhead of the database sessions to be slowing down your site to a noticeable degree you might consider sticking memcached between your web server and the database.

Is there a way to clear some session data from ALL sessions?

In general, I have the following scenario:
Fetch product and its related data from database
Convert fetched data to php 'product' object
cache product object in session
The cache is readonly, i.e customers viewing products on the site.
But there are calls like getProductIdsByCategory($categoryId) and the productIds from these results are cached too, per user, not using the global cache that I've read about.
A problem is that if someone on the admin side adds a new product and relates it to a category, then customers will not have the new productId come up in their cached getProductIdsByCategory until a new session is started.
Is there a way to clear e.g $_SESSION['x'] from ALL sessions on the server when a new product is added? I don't want to destroy all sessions because customers will then lose their logins etc.
Or should I move these cached productId searches to the global cache?
p.s am using a custom built cache, not memcached or similar.
Thanks
By default, the session data is just serialized files somewhere in your filesystem, and it is possible to go modify all of them to remove the information in question (respecting locking so that you don't step on any currently open sessions).
I don't really recommend it, though. What I would recommend is making a method of signalling that this cached data should be refreshed, like a database-stored timestamp that gets looked at when session_start() happens, and if the cached data is older than the timestamp, the cache is flushed.
Sounds to be like you could do with real shared state through a caching system like memcache.
The only other way that prints to mind is have the application check for flags for dirty cache data and delete it itself, or if your cache is in a database in a parsable serialized form write an expensive script to read them all, but that will create nasty lag with requests that have already read the data.
I would go with real shared state than checking for object copies.
Unless you store sessions in a database, clearing any specific bit of data will be tricky.
I would suggest caching in files rather than user sessions. This way you achieve the same benefits, but you get total control over what is cached and when it gets cleared.
To disable all existing sessions for a particular application, simply modify your application to change the name of the session using PHP's session_name('new_session_name'). This function needs to be called before each call to session_start().
This won't actually clear the current sessions, but it renders them no longer useful for this application.
Yes, you should move it to a global cache. Sessions are not meant to be accessed globally, I hardly think it's possible.
<?php session_destroy(); ?> // To delete whole session
// OR
<?php unset($_SESSION['myVar']); ?> // To delete a session myVar
to clear a session value use:
unset($_SESSION['x']);
you may loop on sessions for that

Categories