How long does the instance of a class, object, in PHP last. Is it confined to the running script or will it last for a session? If it does last for a session is this regardless of whether the PHP script has start ed the session?
A simple question but this makes a big difference to me because it will mean user data will survive as an on the server and won't need storing in the session variable. Hence affecting some fundamentals of my design.
Thanks
Colin
the question doesn't really belong to OOP but to PHP behavior in general
All PHP data is going nowhere as well as PHP script itself.
PHP scripts execution is atomic. It's not like a desktop application constantly running in your browser, and not even a daemon with persistent connection to your desktop application. It's more like a command line utility - doing it's job and exits.
That's why using external storage, like file or database is required. But of course you can save only strings there, not instances of variables or anything of the kind. Strings only.
It depends on the way PHP is configured. If PHP is configured as CGI, instances would be lost on each invocation. PHP would be invoked for each http request.
If PHP is configured as a module, then there would be multiple processes handling PHP requests. So, the instance would survive in "that particular" process. But subsequent requests might be handled by a different process.
If you need class instance to survive, you will need to serialize it and store it in DB or file.
If this information is transient (or stored somewhere else) you can store (seralize) it in session. One such example is user's full name which might be required for each http request, so it can be read from DB once and then stored in session.
Example of storing class instances in session : http://www.talkphp.com/advanced-php-programming/3407-storing-class-instance-into-session.html
It's nicely explained here :
How long does an instance variable persist? In Rails? In Java? In PHP?
Related
Is it possible to have two scripts that both run on say a cron jobs, and pass a SESSION variable from Script1.php to Script2.php? I understand the most common usage of SESSION variables is to create the typical unique ID cookie for users accessing a site via the browser and carrying information about that user from page to page. What would happen if I set a SESSION variable in a script that was executed server side and then run another to attempt and pick up the particular variable? Would the server generate a unique ID for itself that would expire after the likely default of 1440 seconds?
My thoughts are that, I build a lot of PHP scripts for things like consuming APIs where there is multiple files that often need to run in some sort of sequence. Instead of passing information from one script to next via MySQL database updates and selects, I'd like to use the more lightweight and seemingly more convenient SESSION variable method.
Session variables are not for passing data between scripts. They are stored by the server, so the cli, which executes php scripts run by cron, would not have a session at all. Sessions are not something that makes the least bit of sense to use for passing data/state/whatever it is you are talking about between two processes. If you want IPC then you need to either use threading or another language. PHP has traditionally used a database of some sorts for sharing data between processes. There is a reason for this.
The short answer to your original question "What would happen if I set a SESSION variable in a script that was executed server side and then run another to attempt and pick up the particular variable?" Is that if the script was executed by the CLI you would get an error trying to access something that wasn't there. If you were accessing it through a script executed by Apache, for instance, you would put the data into the session belonging to the client that browsed to the URI. The next script would not be able to access that unless it was the same client.
You could set and get environment variables for cli scripts to pass data I suppose.
I'm building a login class in php that will use sessions. I wanted to know:
If an instance of this very class will be saved until it is destroyed, even if I move to another page(without destroying it)?
Will I have to rebuild another instance of the class every time (with some saved data in the sessions)?
What is the life of a php class?
PHP variables persist while the program is running... just like any other programming language.
Now, how long does the program actually run? We have to distinguish between:
The PHP interpreter itself (written in C)
Your script (written in PHP)
The PHP interpreter is not designed to share variables between scripts so it doesn't really matter how long it runs.
Your script will run, well, until it's finished: it reaches the last line of finds an exit, die() or return statement. This simple fact should already answer your question. But it's also worth taking into account that there's no point in keeping a PHP script running continuously like a desktop application when it's only used to serve an HTTP request. Unlike other protocols (namely FTP or IRC), HTTP is stateless: each user request starts and closes the connection*.
(*) That's not entirely true (connections can and are normally reused) but doesn't affect the design implications.
Yes, the php class will be destroyed. You can serialize the object and store it in the session, if you choose : Documentation
A PHP object (class instance) acts just like a variable and will be destroyed at the end of the page request. Moreover you cannot store an object in a PHP session. The best you can try is to serialize() it and unserialize() it afterwards to keep your data.
You should see this per request. If you make a new request when going t another page then yes it needs to be rebuild.
What you could also do is Inversion of control or some sort of register setup. This way you can define it once and return an instance.
Example:
$ioc->translate(function() {
# Do stuff load configs. Get data from previous request
return new \Danoon\Link\Translate('../etc/lang/en_US.php');
});
I've done a fair bit of PHP over the years but I'm currently learning ColdFusion and have come across the Application.cfc file.
Basically this is a class that's created once (has an expire date). The class handles incoming users and can set session variables and static memory objects, such as queries. For example I can load site wide statistical data for one user in another thread from the Application.cfc. Something that would usually take a few seconds for each page would make the whole site quick and responsive.
Another example (just for clarification).
If I put an incremental variable that's set to 0 in OnApplicationStart this variable can be incremented with each user request (multiple users) or in OnSessionStart without the need to contact the SQL database since it's constantly in the server's memory under this application.
I was wondering if PHP has a similar file or object? Something that can be created once and used to store temporary variables?
The PHP runtime itself initializes the environment from scratch on every HTTP request, so it has no built-in mechanism to do this. Of course you can serialize anything into common storage and then read it back and deserialize on each request, but this is not the same as keeping it in-memory.
This type of functionality in PHP is achieved by outsourcing to other programs; memcached and APC are two of the most commonly used programs that offer such services, and both come with PHP extensions that simplify working with them.
I have a Symfony2 project, where at the beginning of each session, I create a folder on the server where the user can manipulate and place his files.
I want to be able to delete the user's folder, when he closes his browser
(or any other related event, maybe check for a session timeout?).
How can I achieve this?
PS: I have read somewhere that java has a sessionHandler where you can code your function.
Is there anything similar in php (Symfony2 specifically)?
First of all, you cannot recongnize if a browser is closed by HTML and PHP. You would need ajax and constant polling or some kind of thing to know the browser is still there. Possible, but a bt complicated, mainly because you might run into troubles if a browser is still there (session is valid) but has no internet connection for a few minutes (laptop, crappy wlan, whatever).
You cannot have a sessionHandler which does this for you in PHP because PHP is executed when a script is retrieved from your server. After the last line is executed, it stops. If no one ever retrieves the script again, how should it do something? There is no magic that restarts the script to check if the session is still there.
So, what to do? First of all you want to make the session visible by using database session storage or something like that. Then you need a cronjob starting a script, looking up all sessions and deciding which one is invalid by now and then does something with it (like deleting the folder). Symfony can help as it allows you to configure session management in a way that it stores sessions in the database (see here) as well as creating a task which can be executed via crontab (see here).
The logical part, which contains deciding which session is invalid and what to do with this sessions) is your part. But it shouldn't be very hard as you got the session time and value in the database.
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.