Finish php script before executing - php

I'm making a multiplayer smartphone game where I have PHP as my backend. When a player makes a move info is send to my PHP script which executes the script, and in the end sends some info back to the smartphone. When alot of players a plying atr the same time (Now I have a workload of 2-4 requests each msecond) the response time is a bit long... I have about 3-4 different SELECT queries and 4-5 UPDATE/INSERT queries in my script.
I have been looking into Stored Procedures and are thinking of maybe using AJAX but not sure. What I want to accomplish is to get the response time down on the smartphone by sending the data back as soon as possible in the script and then execute the rest afterwards!
What is the best way to approach this?
Thanks for all your advice in advance ;-)

Ajax is a good option because it will not render all the page and do all queries necessary to it.
Then, have you check your queries : are there all indexes ? Have you avoid multiple join ?
so, 2 ways : ajax, reduce the response transfer (using json with very few information is good) and optimize your database

If you use PHP as Fast CGI (php-fpm) then you can try return response and continue script in "background".
See function fastcgi_finish_request

Related

DB Connection on Ajax

I have a chat on my website, and it runs on AJAX calls. Knowing that the PHP script is being ran 2-3 times per second, is it a bad idea to connect to a database and pull / insert data? I am wondering if it will slow down my PHP significantly, or not change it much at all.
Sorry I can't comment yet, so i don't know if that's your answer..
So basically of course this will cause all lot of traffic on your database. Depending on Webserver this might not be that big of a deal. But if a Clients physic computer is just from 2000, his side will just lag out the tab because his browser is sending all the time requests to your database and is trying to get the answer.
But i think this is the easiest method to get live data, which you need for your chat. But in my opinion I would suggest you to run the AJAX-Request like every 2 Seconds. I don't know what's exactly your purpose. But for a normal chat (not real time data exchange) this will last.
By the way: I am also not sure how you are initializing your AJAX-Request. But i would suggest doing this with jQuery:
$(document).ready(function(){
call_php_ajax()
});
function call_php_ajax(){
$("#div_toinsert").load("ajax.php");
setTimeout(call_php_ajax, 3000) // 3 Seconds
And in your MySQL-Query-File (ajax.php) you perform your queries

PHP & jQuery ajax call without waiting for response

I am struggling with something.
I have an PHP page that does an ajax call to another page using jQuery $.ajax. It sends the request async to the processing page which then returns a response.
This works fine now but we are making some changes to the backend and the processing (SQL stored procedure) that runs is now taking a lot longer like well over 5 minutes. The wait is is fine because we are dealing with close to 200MM records in SQL.
The thing is I need to be able to send the request to the processing page and not have to wait for a response. The processing page fires off the stored procedure in PHP like this:
$query = $dbh2->prepare('exec sp_name :countID');
$query->bindParam('countID', $countID);
$query->execute();
Now again that stored procedure takes awhile to run and we do not need the results of that to be presented back to the user. There is though some additional PHP code that needs to run after the stored procedure but again nothing needs to be send back to the browser.
I am trying to figure out a way that I can make a call to the processing page and it runs the stored procedure and the other code but the user's browser does not need to wait for the response. Right now if the try to click off the page too soon it basically locks up the browser for awhile and does not finish the processing.
Any insight into this would be great.
Thanks in advance for any help.
Sequenzia, if I understand correctly, then I've been here and found a way through this quagmire after a lot of research.
I provided an answer to a similar question a few months ago. Unfortunately, the OP nor anyone else has ever accepted/commented/upvoted/downvoted - nada.
Run a batch file from my website
And here are some useful references :
Running a background script (unix command)
Ref: http://nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/
Ref: http://www.mathinfo.u-picardie.fr/asch/f/MeCS/courseware/users/help/general/unix/redirection.html
How to compose PHP $shortopts and $longopts
This is the way to interpret parameters passed to a PHP script when run from the command-line, or from another PHP script with shell-exec()
Ref: http://www.php.net/manual/en/function.getopt.php
You might look at setting the timeout option for the $.ajax() method. By setting a timeout of maybe half a second or whatever, the ajax will just timeout and go into the error handler (if any).

How do I make scalable PHP for rapid Ajax requests?

I have a program in which an Ajax request goes out to a PHP script that does all the behind the scenes stuff of grabbing the data from the database and then returning it as responseText to be pasted into my HTML to update the page without refreshing. I do this request once every 250 milliseconds (so that means I get 4 hits to the PHP script per second for every user on the HTML page firing the Ajax requests.) I am already seeing the PHP crash with a few computers on at the same time, so I'm guessing the problem has something to do with the PHP getting a lot of requests. Is there a way to do these requests so that a lot of users can get on without this scalability issue coming into play?
First of all firing that much ajax requests ain't a good idea. when the number of users increases, the server load will increase exponentially serving requests. Second thing you need to consider the possibilities of scaling the application and database. I guess you might be returning json_encoded data from server, else make it so.
4 r/s is.. nothing for PHP. So in a short: in order to make PHP scalable; make your code scalable.

PHP display progress messages on the fly

I am working in a tool in PHP that processes a lot of data and takes a while to finish. I would like to keep the user updated with what is going on and the current task processed.
What is in your opinion the best way to do it? I've got some ideas but can't decide for the most effective one:
The old way: execute a small part of the script and display a page to the user with a Meta Redirect or a JavaScript timer to send a request to continue the script (like /script.php?step=2).
Sending AJAX requests constantly to read a server file that PHP keeps updating through fwrite().
Same as above but PHP updates a field in the database instead of saving a file.
Does any of those sound good? Any ideas?
Thanks!
Rather than writing to a static file you fetch with AJAX or to an extra database field, why not have another PHP script that simply returns a completion percentage for the specified task. Your page can then update the progress via a very lightweight AJAX request to said PHP script.
As for implementing this "progress" script, I could offer more advice if I had more insight as to what you mean by "processes a lot of data". If you are writing to a file, your "progress" script could simply check the file size and return the percentage complete. For more complex tasks, you might assign benchmarks to particular processes and return an estimated percentage complete based on which process has completed last or is currently running.
UPDATE
This is one suggested method to "check the progress" of an active script which is simply waiting for a response from a request. I have a data mining application that I use a similar method for.
In your script that makes the request you're waiting for (the script you want to check the progress of), you can store (either in a file or a database, I use a database as I have hundreds of processes running at any time which all need to track their progress, and I have another script that allows me to monitor progress of these processes) a progress variable for the process. When the process begins, set this to 1. You can easily select an arbitrary number of 'checkpoints' the script will pass and calculate the percentage given the current checkpoint. For a large request, however, you might be more interested in knowing the approximate percent the request has completed. One possible solution would be to know the size of the returned content and set your status variable according to the percentage received at any moment. I.e. if you receive the request data in a loop, each iteration you could update the status. Or if you are downloading to a flat file you could poll the size of the file. This could be done less accurately with time (rather than file size) if you know the approximate time the request should take to complete and simply compare against the script's current execution time. Obviously neither of these are perfect solutions, but I hope they'll give you some insight into your options.
I suggest using the AJAX method, but not using a file or a database. You could probably use session values or something like that, that way you don't have to create a connection or open a file to do anything.
In the past, I've just written messages out to the page and used flush() to flush the output buffer. Very simple, but it may not work correctly on every web server or with every web browser (as they may do their own internal buffering).
Personally, I like your second option the best. Should be reliable and fairly simple to implement.
I like option 2 - using AJAX to read a status file that PHP writes to periodically. This opens up a lot of different presentation options. If you write a JSON object to the file, you can easily parse it and display things like a progress bar, status messages, etc...
A 'dirty' but quick-and-easy approach is to just echo out the status as the script runs along. So long as you don't have output buffering on, the browser will render the HTML as it receives it from the server (I know WordPress uses this technique for it's auto-upgrade).
But yes, a 'better' approach would be AJAX, though I wouldn't say there's anything wrong with 'breaking it up' use redirects.
Why not incorporate 1 & 2, where AJAX sends a request to script.php?step=1, checks response, writes to the browser, then goes back for more at script.php?step=2 and so on?
if you can do away with IE then use server sent events. its the ideal solution.

PHP and AJAX, sending new PHP info to page for AJAX to receive, is this possible?

I'm searching on how to do this but my searches aren't turning up things that are talking about what I'm trying to do so maybe I'm not searching with the right terms or this isn't possible, but figured I would ask here for help.. this is what I am trying to do..
I have PHP scripts that are called asyncrhonously, so it is called and it just runs, the calling PHP doesn't wait for a response, so it can go on to do other stuff / free things up so another asynch php process can be run.
I would still like to get back a result from these "zombie" scripts or whatever you want to call them, however the only way I can think of doing it that I know for sure will work is something like make this "zombie" script save its final output to a database and then have my AJAX UI make periodic requests to this database to check if the needed value exists in the place it is supposed to.. which would allow it to get the output from the zombie PHP script..
I am thinking it would be better if somehow this zombie script could do a sort of page refresh to the AJAX ui but the ajax ui would intercept this and just take the received data from PHP and use it as needed (such as display in a DIV for user to see).. basically I'm wondering if you can make PHP force this kind of thing rather than needing to involve a database in this and making AJAX do repeated requests to check for a specific value that way..
Thanks for any advice
No, a background script has no way to influence the client's front-end because it has no connection to it.
Starting a background script, having the script write status data into a shared space - be it a database or a memcache or a similar solution - and polling the status through Ajax is usually indeed the best way to go.
One alternative may be Comet. It's a technique where a connection is kept open over a long time, and updated actively from the server side (instead of frequent client-side Ajax polling). I have no practical experience with this but I imagine it most probably needs server side tweaking to be doable in PHP - it's not the best platform for long-running stuff. See this question for some approaches.

Categories