if on a page i have
echo $_SESSION['user_id'];
and it echo's 1
can i access that value on a page called using ajax (on the same server & domain)
or do i need to pass that value through with the ajax request?
Yes you can access it, the same cookies are, by default, passed with an AJAX request, which is what you need for session (again, by default).
If you look at XHR requests "out of the box", you'll understand that there is generally no difference, in the client or in the server, between a "classic" HTTP request and an XmlHttpRequest.
The only difference is in the client, in two ways: you get the answer without leaving the current page, and you are free to do what you want with that in your javascript.
So in the PHP side of things everything is the same.
One point that might need some attention: if for instance the client does many asynchronous requests that might take some time to process in PHP, you'll want to be careful with the default file-based PHP sessions. An Apache/PHP process that has opened the session will essentially block other requests that also want to access the session. session_write_close() is your friend.
Related
I have a variable that I want to persist between pages. I've tried setting it using POST, and when that didn't work, I used SESSION. Yet in either case, the variable is lost when I go to the new page.
Here is the code when the variable is set:
$_SESSION['filename'] = $boardName;
$debug->alert_code_info($_SESSION['filename']);
And just as a debugging test, I used this line to check if it persisted:
$debug->alert_code_info($_SESSION['filename']);
You can substitute POST for SESSION in the above lines - I've tried that as well, and it doesn't work either.
Why are these variables not persisting from page to page?
Make sure you have session_start(); on both the pages on the top.
Yes, $_POST would work. In that case, please go through this article. Post data in PHP
$_POST is an array that stores data received from an HTTP POST request to a particular page. It is not like $_SESSION variable which persists across the pages.
PHP has "page scope". What that means, is that when a script is run, all variables are created, and when the script completes, all variables are disposed of. It has no persistence. Without output buffering (a whole subject unto itself) for all intents and purposes, as soon as the page is accessed and output generated, the script will be complete. This model is very close to the way HTTP is designed.
As noted, you need some other form of persistence to carry variables between pages. Sessions, databases & datastores, cache, cookies and shared memory are all routinely used in php applications.
Which one is appropriate requires some further understanding of why you need the persistence.
You can also pass variables from one page/script to another using the standard web mechanics of url parameters (automatically placed in the $_GET superglobal), POST variables (automatically placed in the $_POST superglobal) or cookies (automatically placed in the $_COOKIE superglobal).
Some of these are connected, in that php sessions by default utilize a cookie used by the server to identify a returning client.
In regards to your specific question about POST variables, so long as a form is POSTed targetting your script, the POST variables will be available in the $_POST. A much used technique is to either utilize hidden form fields or to set the value of form fields when there is a multi form process, or in the case of error handling.
To be clear, again PHP has no persistence, which is different from some other languages which run under application servers (such as Java with a J2EE server). In J2EE Objects can be created and will live inside the Application server across any number of page requests. PHP in some implementations has some minor persistence capabilities as in the case of database pooling, but nothing intrinsic to the language.
Once you are clear about page scope, and that essentially nothing lives beyond one HTTP request/response, your persistence options should be clearer.
is there any "in-use"-case for the specific PHP-file in AJAX?
For example: On my website there are numerous AJAX scripts running simultanious. The PHP script is already in use for a AJAX script. What does it mean for the other AJAX scripts? Do they connect to a new instance of the PHP script or what? Or am I completely wrong?
As #mudasobwa said PHP is (most of the times) stateless. It's not really PHP which is stateles, but it is HTTP which is a stateless protocol.
So that means every request is completely seperate from each other and they don't know anything about the request before or after. That's why there are things like SESSION, POST and GET to send or share information accross multiple PHP (HTTP) requests.
Also note this is the reason why you need to do things like authentication, database connection and query data every request.
As already mention in comments each request is separate.
However, if you are using sessions, in the php files requested by ajax, and the same request takes some time to process, your second ajax might hang, if this is trying to access the same session. This is due to the fact that php will lock your session file until it knows that the locking thread is done with it.
What you can do (if you are using session), is to close the session file by calling "session_write_close", when you know that you don't need to update the session.
http://php.net/session_write_close
Is it possible to have a php script pause at a certain point wait for an ajax response, then continue executing?
If not, what is the most appropriate way to store the current state of a script (all defined variables ect) untill it in invoked again?
Making it wait for an ajax response which could never come sounds like a very bad plan (apart from being impossible due to the nature of http as a stateless protocol).
What's wrong with using session to persist user data (you can store objects in the session)? It won't serialize the whole state automagically though.
Not how php works, or ajax really either. Each request is independent. You can use a session.
I think you are looking for Cometlink text - which is a form of reverse Ajax which holds the connection open indefinitely - although I don't think you'd have a PHP script just wait for it...
If you want to get in your php script response that you would normally access via ajax then just use curl functions. Curl will wait for the response to arrive.
Is it possible to achieve true multi-threading with Ajax? If so, how? Please give me some related information, websites or books.
It depends on what you mean by "multithreaded".
Javascript code is distinctly singlethreaded. No Javascript code will interrupt any other Javascript code currently executing on the same page. An AJAX (XHR) request will trigger the browser to do something and (typically) call a callback when it completes.
On the server each Ajax request is a separate HTTP request. Each of these will execute on their own thread. Depending on th Web server config, they may not even execute on the same machine. But each PHP script instance will be entirely separate, even if calling the same script. There is no shared state per se.
Now browsers typically cap the number of simultaneous Ajax requests a page can make on a per host basis. This number is typically 2. I believe you can change it but since the majority of people will have the default value, you have to assume it will be 2. More requests than that will queue until an existing request completes. This can lead to having to do annoying things like creating multiple host names like req1.example.com, req2.example.com, etc.
The one exception is sessions but they aren't multithreaded. Starting a session will block all other scripts attempting to start the exact same session (based on the cookie). This is one reason why you need to minimize the amount of time a session is opened for. Arguably you could use a database or something like memcache to kludge inter-script communication but it's not really what PHP is about.
PHP is best used for simple request processing. A request is received. It is processed and a response is returned. That response could be HTML, XML, text, JSON or whatever. The request could be an HTTP request from the browser or an AJAX request.
Each of these request-response cycles should, where possible, be treated as separate entities.
Another technique used is long-polling. An HTTP request is sent to the server and may not return for a long time. This is used for Web-based chat and other "server push" type scenarios. Sometimes partial responses will be flushed without ending the request.
The last option (on Unix/Linux at least) is that PHP can spawn processes but that doesn't seem to be what you're referring to.
So what is it exactly you're trying to do?
You can't actually multi-thread but what a lot of larger websites do is flush the output for a page and then use Ajax to load additional components on the fly so that the user sees content even while the browser is still requesting new information. Its a good technique to know but, like everything else, you need to be careful how you use it.
I have been poking around in PHP for OOP and I noticed something... Objects are re-instantiated each time the page is refreshed. The problem is that I want the object to keep certain information in class variables for the whole time that someone is on a website.
Is there some sort of way to keep an
object alive the whole time that
someone is surfing on the website?
What alternatives are there to my
problem?
It would be really helpful to have example too!
You can use Sessions to keep data associated to one user between different pages (quoting) :
Session support in PHP consists of a
way to preserve certain data across
subsequent accesses.
See the Session Handling section of the manual, for more informations about sessions.
PHP isn't stateful. Every page load is a one time event. You can persist data with sessions, or by storing information in a database.
A php script has to exit before apache can serve the page, so if you really want to do that, one thing you can do is serialize and store all the objects that you want to persist and use session cookies to keep track of the users
PHP isn't statefull every request is a new process on the server
Your best bet is to use session data and hand the session data to the objects when you instantiate them. Have the contructors pull the data they need out of the session, and you'll essentially have the state fullness you need.
you can acess sesion using
$_SESSION['stuff'] = $data;
then you can use your objects like
$x = new DataStore($_SESSION['stuff']);
if theres data in the session the object will populate itself from that data. Otherwise it will default to its standard init.
Even when approaches like serializing objects and then deserializing them is useful, you have to make sure you understand first why your objects "disappear".
HTTP, the protocol used to retrieve pages and other resources from Web servers, is stateless. It basically means one request knows nothing from another request, even when it came from the same user. Think of it this way, when you request your PHP page, the script is run and after it finishes Apache sends out the result to you. When you request the page again, it does the same thing as if it was the very first time you did it. It's stateless.
There are techniques to keep state between requests (make it to not forget your objects) and those involve things like cookies or URL rewriting. But you have to keep in mind the stateless nature of HTTP (and thus your PHP script) when developing Web applications.
SESSIONS are good, i use them to hold object state in some of my PHP programming.
Or a better solution would be to use Flex so you don't have to worry about the stateless HTTP protocol...