Does PHP have inside cache? - php

I want save the editor content for 30s, and upload the content to server. If the browser have some problem or it closed. user can restore the content next time they login.
But I think, if the content save to the SQL, not good. I wondered if PHP has a cache function. Like memcache. The content is put in the cache, if the server restart, the cache can clear. and do not need write in SQL.
so, does PHP have a cache mechanism? Or can you give me a solution handle the content, must run quickly and the server must not require pressure.

The client side has nothing to do with PHP, by the time the user receives the output that is the page, all of the PHP has been transformed. You could make this PHP's business, by means of pushing your cache data up to the server using AJAX. So, you need two solutions: one to manage data on the client side (say, using Javascript) and one to manage data from the client side on the server side (with PHP).
This is if you still want to use PHP, when you more than likely don't need to. Anyway, PHP does not have a built-in cache implementation that I am aware of, other than perhaps using $_SESSION, you'll need to roll your own.

there's no standart "inside" cache in php. You'll have to use either your own system, html5's localStorage or memcached/any other plugin. Memcached is definetely recommended though.

PHP does have inherent cache implementation. It's called APC(alternative PHP cache). It should be turned on in php.ini.
APC is of course server-side technology and has nothing to do with browser and javascript technologies. It's used for same reason memcached is used(and few others) - to give SQL Server some slack.

Related

PHP / MySQL auto update clients

I'm writing a website using PHP / MySQL. The website should allow users browsers to be automatically updated when a table is updated in a database (which is caused by someone inserting something though the PHP site). Basically, if the state of the table changes other users on the website should immediately see the changes.
I'm relatively new to PHP / AJAX and other web technologies. The only way I can think of doing this is to have the clients manually recheck the database every second or two via a timer (but this seems like a lot of wasted bandwidth). Is there some way to have the users automatically notified when the database changes?
Thank you!
You already had the solution in mind. You can use ajax to automatically check for changes.
It's not possible for the server to contact you when something has changed. It doesn't have to be bandwidth intensive when you lower the retrieval intervals. You can have Ajax check for a blank page with as little as possible text. That way the bandwidth usage wont be too bad.
Facebook does it this way too.
1) AJAX Polling.
As you say, use ajax to call the PHP on the server side to get
updates.
2) HTML5 Websockets.
Websockets are a new feature of HTML5 which allow the browser to keep a bi-directional TCP connection open to the server, where data can be transmitted both ways without polling. Currently this isn't as widely supported as ajax polling is.
3) Java Applet/ActiveX control.
Generally the most undesirable solution because of the user having to install third party software.

How to update UI when data has changed?

I have a series of XML files which can be retrieved, edited and saved by a User. My intention is to allow multiple Users to edit these files at the same time. Many parts of these XML files relate to content displayed in the browser UI for example a <name>My title</name> node is displayed and can be edited.
The technologies I'm using are Javascript, PHP, and a master XML file containing references to other XML files (both master and referenced files can be edited in the UI). The server is WebDAV enabled, and WebDAV methods are used via YUI3's io module to handle retrieval, saving, collection moving etc.
How do I go about updating UIs where these resources are being used, based on the contents of the edited and saved XML file(s)?
I know I could probably run setTimeouts and whatnot to check for updates, but it seems more intuitive to make the UI respond only when data is changed.
cheers!
The feature you're describing is similar to a technique known as server-push. What you're asking to do is a very tricky thing for a web app (especially for PHP, which is built around the idea of a request that gets served and the script terminating).
HTML5 is introducing technologies such as websockets for maintaining a persistent connection to a server, you could look into websockets as a solution, but it's a brand-new technology and I don't think the spec is even finalized yet, so it will only be implemented in the very latest versions of browsers, if at all.
You've already mentioned AJAX polling (driven by setInterval), but you've also noticed that it's problematic. You're right of course, it is, local data can become stale in the interval between polls, and you'll generate a lot of traffic between the server and any open clients.
An alternative is so called "long-polling". The idea is the client starts an AJAX session with the server. On the server the script invoked by the client basically just sits there and waits for something to change. When it does, the server notifies the client by sending a JSON/XML/whatever response and closing the AJAX session. When the client receives the response, it processes it and initiates a new AJAX connection to wait for another server response.
This approach is almost instantaneous, because data gets pushed to the client as soon as it's available. However, it also means lots of open connections to the server and this can put the server under a lot of load. Also, PHP scripts aren't really meant to run or sleep for a long time due to the request-response model the language is built around. It is possible, but probably not advisable to follow this approach.
How do I implement basic "Long Polling"? has some examples of the long-polling technique.
Good luck!

Creating a live checkers-like web app with PHP, JS, CSS and HTML?

I want to create a live, checkers-like app, which will work like this: There will be multiple icons/avatars displayed on this checkerboard like surface. I want to have a command prompt beneath this board, or some other sort of interface, that will allow them to control a certain avatar, and get it to preform actions. Multiple users will be using it at one time, and I will all be able to view the other user's changes/actions to the checkerboard.
What I'm wondering is: what's the best way to do this? I've got my HTML, CSS, and JS approach down, but not my data storage method. I know that, using PHP, I've got the choices to use either: file-based storage, MYSQL, or some other method. I need to know which is better, because I don't want to have server-lag, poor-response time, or some other issue, especially in this case since actions will be preformed every other second 2 or so, by these multiple users.
I've done similar stuff before, but I'm wanting to hear how others would handle it (advice, etc.) from more experienced programmers.
Sounds like a great project for node.js!
To clarify, node.js is a server-side implementation of javascript. What you'll want is a comet based application (a web-based client application that receives server side pushes instead of the client constantly polling the server), which is exactly what node.js is good at.
Traditional ajax calls for your clients to poll the server for data. This creates enormous overhead for both the client and the server. Allowing the server to push requests directly to the client without the client repeatedly asking solves the overhead issue and creates a more responsive interface. This is accomplished by holding asynchronous client connections on the server and only returning when the server has something to respond with. Once the server responds with data, another connection is immediately created and held by the server again until data is ready to be sent.
You may be able to accomplish the same thing with PHP, but I'm not that familiar with PHP and Comet type applications.
Number of users and hosting costs will play into your file vs DB options. If you're planning on more than a couple of users, I'd stick to the database. There are some NoSQL options available out there, but in my experience MySQL is much faster and more reliable than those options.
Good luck with your project!
http://en.wikipedia.org/wiki/Comet_%28programming%29
http://www.nodejs.org/
http://zenmachine.wordpress.com/2010/01/31/node-js-and-comet/
http://socket.io/ - abstracts away the communication layer with your clients based on their capability (LongPolling, WebSockets, etc.)
MySQL and XCache !!!!
Make sure you use predefined statements so MySQL does not need to compile the SQL again. Also memtables could be used to use memory storage
Of course make use of indexes appropriately.
If the 'gamestate' is not that important you can even store everything in XCache.
Remember that XCache does not store data persistently (after Apache restart)

html5 offline caching with php driven sites

I have a simple php driven website running and I'm trying to figure out how it treats php pages. Some of my php documents are routing logic and some just includes for individual pages. How do i go about making this work offline?
What I though was that I'd have to re-create the routing logic in javascript. Is that my only option? In that case, is it even possible to have the site be driven by php while online and switch to JS offline? I can't make sense of it.
If your site is fairly static, HTML5's cache manifest may get you most of the way there. Have PHP output a cache.manifest file in the correct format with all your routing system's URLs and those URLs will be stored locally in a compliant browser. Attempting to access them will pull them out of the cache if possible.
If you're looking for something more dynamic, though, you're going to have to do more legwork.
Here's some good info on offline caching.
It is important to remember that PHP is processed on the server. The result of your PHP code is all that is sent to your browser. Your browser has absolutely no knowledge that PHP was even used to make the page!
If you have some dynamic code that must run offline, then you must use Javascript. If this is just for testing on your own machine, put a web server running PHP on your dev machine and acccess it via http://localhost.
HTML5 offline caching does not work to make your pages interact; it works only to make a particular page available offline. Basically, it works on a URL-by-URL basis. If you absolutely need offline functionality, you will be forced to make it work in JS.
Also, make sure your manifest includes all resources used by all pages.
Hope this helps!
It seems obvious not to use any server side scripting language file while caching it in your browser. PHP/JSP/ASP etc all are server side language we cant fulfill the request forwarded by client that need to be generated dynamically and most importantly there is no server running on client side. SO , i think we should go for JS whenever we want to do such things.

PHP sessions in a load balancing cluster - how?

OK, so I've got this totally rare an unique scenario of a load balanced PHP website. The bummer is - it didn't used to be load balanced. Now we're starting to get issues...
Currently the only issue is with PHP sessions. Naturally nobody thought of this issue at first so the PHP session configuration was left at its defaults. Thus both servers have their own little stash of session files, and woe is the user who gets the next request thrown to the other server, because that doesn't have the session he created on the first one.
Now, I've been reading PHP manual on how to solve this situation. There I found the nice function of session_set_save_handler(). (And, coincidentally, this topic on SO) Neat. Except I'll have to call this function in all the pages of the website. And developers of future pages would have to remember to call it all the time as well. Feels kinda clumsy, not to mention probably violating a dozen best coding practices. It would be much nicer if I could just flip some global configuration option and VoilĂ  - the sessions all get magically stored in a DB or a memory cache or something.
Any ideas on how to do this?
Added: To clarify - I expect this to be a standard situation with a standard solution. FYI - I have a MySQL DB available. Surely there must be some ready-to-use code out there that solves this? I can, of course, write my own session saving stuff and auto_prepend option pointed out by Greg seems promising - but that would feel like reinventing the wheel. :P
Added 2: The load balancing is DNS based. I'm not sure how this works, but I guess it should be something like this.
Added 3: OK, I see that one solution is to use auto_prepend option to insert a call to session_set_save_handler() in every script and write my own DB persister, perhaps throwing in calls to memcached for better performance. Fair enough.
Is there also some way that I could avoid coding all this myself? Like some famous and well-tested PHP plugin?
Added much, much later: This is the way I went in the end: How to properly implement a custom session persister in PHP + MySQL?
Also, I simply included the session handler manually in all pages.
You could set PHP to handle the sessions in the database, so all your servers share same session information as all servers use the same database for that.
A good tutorial for that can be found here.
The way we handle this is through memcached. All it takes is changing the php.ini similar to the following:
session.save_handler = memcache
session.save_path = "tcp://path.to.memcached.server:11211"
We use AWS ElastiCache, so the server path is a domain, but I'm sure it'd be similar for local memcached as well.
This method doesn't require any application code changes.
You don't mentioned what technology you are using for load balancing (software, hardware etc.); but in any case, the solution to your problem is to employ "sticky sessions" on the load balancer.
In summary, this means that when the first request from a "new" visitor comes in, they are assigned a specific server from the cluster: all future requests for the lifetime of their session are then directed to that server. In practice this means that applications written to work on a single server can be up-scaled to a balanced environment with zero/few code changes.
If you are using a hardware balancer, such as a Radware device, then the sticky sessions is configured as part of the cluster setup. Hardware devices usually give you more fine-grained control: such as which server a new user is assigned to (they can check for health status etc. and pick the most healthy / least utilised server), and more control of what happens when a server fails and drops out of the cluster. The drawback of hardware balancers is the cost - but they are worth it imho.
As for software balancers, it comes down to what you are using. For Apache there is the stickysession property on mod_proxy - and plenty of articles via google to get this working with the php session ( for example )
Edit:
From other comments posted after the original question, it sounds like your "balancing" is done via Round Robin DNS, so the above probably won't apply. I'll refrain from commenting further and starting a flame against round robin dns.
The easiest thing to do is configure your load balancer to always send the same session to the same server.
If you still want to use session_set_save_handler then maybe take a look at auto_prepend.
If you have time and you still want to check more solutions, take a look at
http://redis4you.com/articles.php?id=01..
Using redis you are fault tolerant. From my point of view, it could be better than memcache solutions because of this robustness.
If you are using php sessions you could share with NFS the /tmp directory, where I think the sessions are stored, between all the servers in the cluster. That way you don't need database.
Edited: You can also use an external service like memcachedb (persistent and fast) and store the session info in the memcachedb index and indentify it with a hash of the content or even the session ID.
When we had this situation we implemented some code that lives in a common header.
Essentially for each page we check if we know the session Id. If we dont we check if we're in the situation whehich you describe, by checking if we have stored sesion data in the DB.Otherwise we just start a new session.
Obviously this requires all relevant data to be copied to the DB, but if you encapsulate your session data in a seperate class then it works OK.
you could also try using memcache as session handler
Might be too late, but check this out: http://www.pureftpd.org/project/sharedance
Sharedance is a high-performance server to centralize ephemeral key/data
pairs on remote hosts, without the overhead and the complexity of an SQL
database.
It was mainly designed to share caches and sessions between a pool of web
servers. Access to a sharedance server is trivial through a simple PHP API and
it is compatible with the expectations of PHP 4 and PHP 5 session handlers.
When it comes to php session handling in the Load Balancing Cluster, it's best to have Sticky Sessions. For that ask the network of datacenter who is maintaining the load balancer to enable the sticky session. Once that is enabled you'll don't need worry about sessions at php end

Categories