Where to keep the globals variables in PHP? - php

I am used to use Java and Spring Framework. But not so long ago I started learning PHP , to get familiar with another kind of language.
I am trying to write a simple thing for drawing using html canvas, so more then 1 user can use that at the same time to draw.
In Java i would use a class variable in controller to store the picture draw by users. And every 1-2 seconds users send the request with the new data they have drawn, so i can add the changes to the global variable. and then send the changes to every user. When a new user enters, the server sends the whole picture to him.
So, my question is, how can i store an application global variable in PHP? like in this example with picture...
As i see, after finishing, the PHP halts and all the variables die with it, right? So is there any way to make a variable application global? So i can get access to it from different parts of application?
I can save it to text file before finishing the script. and every time new request happens, read it again from text file, make changes and then write back to text file... but it's so crazy... isn't there any way just like in Spring Framework and Java that i used before?

You need a form of persistent storage. By persistent, I mean storage that is not based on an individual user's session like the $GLOBALS array is. PHP Sessions are useful for storage for a single user, but one user cannot access the session data of another user.
Persistent storage can be achieved a few ways. Some options: checking a row in a database table or storing a value in a file like you mentioned.
Database storage
Check out php's mysqli_query() for more information on doing this via a database. This will require knowledge of MySQL syntax.
File storage
Check out php's file_get_contents() and file_put_contents() for examples on how to easily interact with retrieving data from files and setting data in files.

As DevZer0 answered - you want to use sessions. More information about session you will find in the php manual: http://www.php.net/manual/en/intro.session.php

Related

PHP Beginner: Where and how are objects stored?

In an app written in PHP (e.g., a social network), let's say that 10 users (signed-in) are browsing the website.
In PHP code, there is "user" object created to store users data and to pass values to other functions and classes.
Question: When these 10 users go to user.php, which has code to create "user" object, how are these objects stored in memory in PHP? Do they not conflict? Is each one of the "user" objects are uniquely stored in the memory or would one be overwritten by another?
For example, user a visits first so object "user" contains his/her data but when user second visits, the "user" object in memory is overwritten so when first user calls the object, it's the second users data retrieved.
Or, is it unique?
I want to understand object in PHP as a newbie, please explain it simply because none of the web pages I found regarding OOP explains this.
PHP is a CGI application, that means, it's being started and terminated on each request.
a client sends a request to the web server
the server starts PHP and passes the request to it
PHP allocates a chunk of memory for your script
your script is being executed, all objects it creates are stored in that chunk of memory
you script generates some html, this html is sent to the client
the memory is being freed and PHP is stopped
If you have 10 clients requests coming at the same time, 10 copies of php will be started and 10 independent memory chunks will be used. So, no, objects from different requests do not interfere.
(Note: this explanation is deliberately simplified, there are actually different php setups and persistence options).
The best way to learn this is to install php on a local PC or Mac and then create a php info file
<?php
phpinfo();
?>
... then open it in your browser...This will show you all the settings on your server for php and other things.
Regarding the answer to your question, it's a bit more of an advanced topic for a newbee, but php sessions are what do the work of keeping user info. They usually work off a session id which is unique to the user for a small amount of time, and they dynamically allocate memory or disk space/flat files or a database (again see the settings above) to store the relevant data.
Unfortunately for you none of this is "automatic" you have to create the scripts to make it happen and behave in the way you want. Asking questions on this site is a good start...
You need to look at object design patterns in relation to php which is quite a big subject in its own right. There is an excellent Apress book called 'PHP Objects, Patterns and Practice' which explains some of the more common patterns and how you might use them and would be a good place to start learning.
The users information is all stored in a database, the user object will have to retrieve this data each time the page loads.
The object know what user is looking at the page because of their session_id, which in a nut shell is a random id given to you, stored in a cookie.
using the session_id you can retrieve the correct information form the database.

javascript object: is there a way to store in a PHP session var?

I'm using JS Objects to sort and filter a table but I need to store the original table data in case the user wants to return to it. I'm just wondering if there's an easy way to pass the object's data to a PHP session var, via AJAX, and retain stuff like the key/value relationships without doing a lot of heavy lifting.
Build a JSON-string of the object and store this string.
JSON.stringify
It's not possible.
On the client side, the session is identified by a cookie. The session ID is all you've got.
On the server, the session data is stored in a binary file, one file per session (typical scenario).
So you can't touch the contents from the session from the browser without help from the server.
And second: it's not "light". In an app I've been working on, modern computer and virtually no load yet, loading the session seem to be taking around 250ms, 10 times longer than the response time for the whole page when starting from scratch.
In summary:
you cannot touch session variables without writing a script on the server that handles the data
It's not "light".

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 ajax 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.

What happens to a class in PHP once its been instantiated?

I'm just playing around with some PHP and was wondering what happens when an object from a class is created within another PHP script?
I assume once its created and been processed their is no way of then going back and 'playing' around with it from another script?
The idea is i'm trying to create a kind of deck of cards using a card class, each card has specific data that is added to each individual object to make it unique, suit, value etc. Once its created i need to be able to go back to specific cards to use them. In java i'd have an arraylist of card objects, i'm not sure how to approach the same area in PHP.
Thanks.
There is no problem passing objects around inside a php script, your problem is that php is that the webserver calling the script is essentially "stateless". i.e. every time someone posts the url from a browser a complete fresh copy of the php program is fired up.
To save data between times there are several options:-
One is to use $_SESSION variables which are associated with a user session but $_SESSION itself is an array so it gets really clumsy holding complex structures here, also , it sounds like you want to share the deck between users.
You could serialise your object and store it in a file -- which is OK as long as its not updated very often -- but if its updated by every user they will start overwriting each others changes.
Much better is to store the deck in a database (SQLITE is usually built into php) so that several users can share and update in a controlled manner.
Another good option would be to use one of the popular data caches such as "memcached" which will cache the data between calls to the script.
To reuse an object between page calls seems to be your issue. Maybe you can serialize the object and store it in database and pick it up back?? Check php.net/serialize Let know how it goes.
What you could do to keep the objects available to you is to serialize the objects and store them in a database table. If you link a game ID or something similar to the cards then you can retrieve them later using this game ID.
I don't know if the cardgame you are writing is realtime, using a database might be too much overhead. Another possibility is to use an existing caching solution, like for example Memcache.
So you want to create a serverside coded cardsgame? Good luck!
It is possible to do this, tho I think a script like a javascript you are talking about is much more suitable.
You could make a function that initialises a deck of cards and work with indexes etc. Save your things in cookies / sessions and work with postbacks. It's gonna be a hell of a job tho in my opinion compared to jscript.
Tho when you think about it, you could use ajax to make this game feel better for the user :).
Php scripts are not like Java server apps.
Where your Java server will run for a long time, your php script will just be a one time thing.
Instead of this kind of process : user make a request to Java-run server, server receive the request in one of it's infinite loops, server process it, server send the response, server wait for new request; you have this kind of thing : a webserver (Apache, Nginx, whatever other webserver) receive the user's request, understand it needs to be interpreted by php, starts a php child, this child do what's in the script, send its answer, dies, the server wait for new requests.
So, when a php script ends, nothing (in good case) is left from it.
But, a php script can use persistent storage on the server so another request can read from it. That's why you have files, databases and even shared memories functions.
If the games state is for one user only, you can use sessions (usually files) to store your deck object. If it's meant to be used by multiple players, you should store it after serialization in a database.

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!

Categories