persistent data in php question
OK Ive written this neat javascript 'thing' using jquery and ajax. Its all based on the idea that a div has an attribute that lets you write inside the div. (contenteditable=true). I thought it would be cool to make a chatroom type thing out of it, and holy cow its doing some cool stuff(*), but I have an issue.
Using ajax I post to a php page that takes the posted data (x,y, text, id) and stuffs it into a JSON-like object. Without writing to a database (overkill I think), how can I make this data persist? See the problem? : The variables in a php page are essentially vapor after the page has ran, so my javascript a开发者_Go百科jax call to retrieveNewJSON() would find nothing.
*using jquery effects and setting colors I have variably placed text that scrolls and evaporates, matrix style, for example. Also, a cursor is placed in the div where the user clicks.
You have to store the data somewhere. If you don't want to use a full blown database you can store them in flat files (ie: txt) and use PHP's file functions to handle the files.
Of course this is not very scalable, and I'd strongly recommend using a database if you are going to be using this a lot.
You could use cookies (client-side) or session variables (server-side), or you could write to a file for longer-term storage.
You could use a the $_SESSION
variable to persist data.
// Call at start of PHP script
session_start()
//....
// Store object
$_SESSION['obj'] = json_encode(obj);
in your pull script:
// Call at start of PHP script
session_start()
// Retrieve object
echo $_SESSION['obj'];
Note that when using sessions you have to make sure that you call session_start()
at the top of every php script that uses the session.
I would not recommend trying to store this in a file unless you are supporting a very low number of users and have taken proper data sanitation steps to physically write files to the server. If you need this to persist past the length of a session you should be using a database.
It is worth noting that you can't update a users session without some other form of centralized storage. Unless you have some sort of long-polling / comet type setup you will have to have some sort of central storage place. Something I would take a look at would be memcache.
If you want to avoid using a database engine (which would have a lot of overhead for a multiple-read, multiple-write app like a chat room anyway), you might look at a simple object store like memcache, couch, or mongo. Files are also a valid option, provided you store them outside of the Web root with proper permissions. Bottom line is, you'll have to use some sort of storage engine on the back end in order to make the data shareable across multiple user sessions.
If this is simply a tech demo or a proof of concept, I wouldn't worry too much about overhead right away.
精彩评论