dynamically update php website - php

Ok... I'm rather new to php (and I know this is probably a dumb question) but I am in the process of hooking up a C++ socket program to a php website.. Currently I can send strings to the website and all works well... Except... it only displays the stuff sent ONCE the php finishes executing...
Solutions I think will work:
1. Make the page somehow run echo's whilest executing
2. find a proper solution, i.e. setup a tcp connection and maintain throught the user sesion (how??) then execute a script which prints to the page apon receiving data
I've tried flush... didn't work
Actually, after thinking about it... Is there a solution where I can maintain a socket tcp connection even if the client changes page? That would be useful... Heres the source:
server(c++):
http://pastebin.com/QfaUrF92
client(php):
http://pastebin.com/hZXKsGN0
please note that I know how crap the code is.. It's just testing and fiddling to figure out what I can do and how I can do it
edit:
I'm trying to impliement my own Long Polling system through connecting a php session to a C++ server... I'de be willing to throw away sessions if it's gonna be dificult, but in the end I would love to be able to maintain a session so that I can fork a process to manage the client through out their browser changing pages

PHP is executed server side, so once the page has been generated it's static. If you need the page content to constantly be updating, you can either use web sockets or ajax. Basically, AJAX will let your browser speak to your server using Javascript once the page has been rendered. Libraries like jQuery make it very simple.
From the jQuery docs (http://api.jquery.com/jQuery.post/):
$.post("test.php", { name: "John", time: "2pm" })
.done(function(data) {
alert("Data Loaded: " + data);
});

You can use NodeJS. It is server side JavaScript.
Using NodeJS you can build a socket connection between the browser page and your web server. Using this you can push data to the browser at the will of the server.
But it might take you some time to get started.
Recommended reading:
www.nodejs.org
www.nodebeginner.org
socket.io
hacksparrow.com/tcp-socket-programming-in-node-js.html

Related

PHP while(true) loop for file updates

I've got the following problem at hand:
I'm having users on two seperate pages, but saving page input to the same text file. While one user is editing, the other can't. I'm keeping track of this with sessions and writing changes and who's turn to edit it is in a file.
Works fine so far, the output in the end is quite similar to a chat. However, right now I'm having users manually actualize their page and reload the file. What I'd like to do is have the page execute a redirect when the file-timestamp changes (to indicate that the last user has saved their edits and its another users turn). I've looked into javascript shortpolling a little, but then found the php filmtime function and it looks much easier to use. Well - here's what I got:
while(true){
$oldtimestamp=filemtime(msks/$session['user']['kampfnr'].txt);
$waittimer=2;
$waittimer++;
sleep($waittimer);
$newtimestamp=filemtime(msks/$session['user']['kampfnr'].txt);
if ($eintragszeit2 > $eintragszeit1){
addnav("","kampf_ms.php?op=akt");
redirect("kampf_ms.php?op=akt");
}}
In theory, while the user sees the output "it's ... turn to edit the file." this should loop in the background, checking if the file has already been updated, and if yes, redirect the user.
Practically this heavily affects server perfomance (I'm on shared hosting) until it breaks with a memory exceeded error message.
Is something wrong with the code? Or is it generally a bad idea to use a while loop in this case?
Thanks in advance!
PHP language should be only used to generate web content (client do a request to the server => server calls the required script, and returns the response to the client).
Once page is loaded and displayed to the client, the connection is closed, so Internet can die, the client isn't informed...
So with an infinite loop, not only the client can wait for response... an infinite time, but also the server may be heavy impacted because of load... Effectively It is a really bad idea :)
PHP can't be used to make a bidirectional communication: it is just called to build web pages that client demands, and so he can't do anything "in the background" (not directly, effectively you can call an external script, but not for notify a client...)
Also, to do a bidirectional communication, php and "regular" http is not good, because of client / server architecture (the server only answers client request, it is passive)
I can suggest to use WebSocket protocol, to do a chat application:
http://socket.io/
https://en.wikipedia.org/wiki/WebSocket
But for that, you need to use an "active" server solution, such as node.js or ruby (depends of your server capabilities...)
The other way if you want to stay in php is that client makes Ajax request every 10 seconds, for example, to call a php script which check the file, and send back a message to the client if file is updated, but it is really deprecated, because of heavy performance loss, so forget it immediately.

Performance issue in continous ajax requests?

I created a ajax chat application something like this to check & get messages every second. and it works fine.
function get_messages(user_id) {
$.ajax({
type : "POST",
url : "messages/get_messages",
cache : false,
data : {
user_id : user_id
},
success : function(data) {
if(data != '') {
var obj = $.parseJSON(data);
var messages = obj.messages;
}
}
});
setTimeout(function() { get_messages(user_id) }, 1000);
}
My question is, When lot of people use this application a lot to Ajax requests to server every second, is there any performance issue or server issue in doing like this, . What is the best practice for doing this ??
Thank you for your valuable suggestions :)
The best way to do chats like this is having the "chat window" properly said as an <iframe> with a permanent connection to a script that will remain running and feeding the client with the new messages so you don't have to overwhelm the server with AJAX requests. This can be achieved by calling a ob_flush() (just to make sure) and flush() after printing new stuff, causing the client to receive the updates immediately. But first you have to prepare the PHP to behave properly by doing some settings:
ini_set('zlib.output_compression', 'off');
ini_set('output_buffering', 'off');
set_time_limit(0);
If you are going to use sessions, don't forget sessions are locked to prevent concurrent writes, so after gathering the information you need from $_SESSION you must release the session by using session_write_close() otherwise the user will be unable to post messages etc.
Your script should also check for inactivity and output something to the client if the chat window remain idle for more than a couple minutes. It prevents the connection from being terminated by the browser. It doesn't have to be anything visual, something commented like <!-- keep alive --> will do.
Now, where you gonna get the new messages from? There are a couple options for doing that:
Sockets. You can have this Chat Server application running in server-side that all the Chat Window PHP scripts will connect to to be fed with the new chat lines. When a user submit a new message, its sent to the Chat Server and it broadcast to the Chat Window scripts. This Chat Server can safely be written in PHP too!
A file. The easiest way. Every Chat Window PHP script open this same file for read-only, and fseek() to its end. Loops checking if its !feof() a couple times per second to read the new lines from it, if theres any. When a user send a new message you just have append this message to the file and the trick is done.
SQL. Not recommended because every Chat Window PHP script will open a new connection to the RDBMS and eventually will reach its limit, but you can try SQLite that don't use RDBMS.
Using regular Ajax/Php for this task is not preferable. As you stated that what if there is alot of users, each user will query the database every second.
This puts too much overload on your server and the users will not have realtime communication with each other.
I would suggest you to use node.js for this task. To make it cross-browser compatible you need to use a framework of node.js which is socket.io
So the final verdict, use node.js
You can learn node.js
http://www.nodebeginner.org/
There are very good tutorials in the web.
lynda.com has also very good tutorial on node.js

How can I connect to a server through JavaScript where my PHP program is housed?

I am writing an Android App, and already have a working program written in HTML and PHP. Using the two, they contact an API with a user customized lookup on the html page, which then sends to the PHP page, contacts the API with the customized search, gets a result, and the php outputs to a html page again.
I know PHP cannot work on Android, but I plan on using PhoneGap. With PhoneGap, I can run JavaScript, HTML, and CSS supposedly. I have also read that a solution with Android being unable to understand PHP is to connect to a server (my computer) which can run the php for me, and then output it in a way the phone can understand.
My plan is to use JavaScript, which PhoneGap can understand, to connect to my computer, and have it run the PHP and output the page in HTML which again, PhoneGap can understand.
If this is absurd, please let me know... Otherwise I'd greatly appreciate it if someone could push me in the right direction in a JavaScript function that would allow me to authenticate myself, connect to my computer, and tell it I'd like to use a certain PHP file.
We had the exact same problem when developing our application for Android as well as for iOS. Like Austin told you already you have to make use of AJAX.
W3schools - AJAX
I recommend you however not to use jquery if it's only needed for a few simple things because it's fairly heavy because of the big script it has to load. So if you can reduce the amount of code, please do so by learning the real JavaScript instead of jQuery.
Also, what we did is writing our own APIRequest.js object. When calling this object like so:
var result = new APIRequest('functionname', {param1:value, param2:value})
This is a fairly easy approach to connect to your php which will run off course on your server somewhere in a foreign country or your pc.
As you can see we insert a functionname, we have developed our API as a fairly simple OOP php thingy that allows us to put a functionname.php in a certain folder and it will be read by de script and then select that function. Database connections and stuff like that will be aranged in the index of the api. With this approach you can make special functions, server-side, for every unique handling.
I am telling you this because you are making use of JavaScript. I'd like you to understand that it is not safe! It as as safe as a JavaScript application on your computer. It is possible for a hacker to download the .apk to his computer, run it in the simulator on his pc and make edits through his console. And thus meaning, he can change your whole code (at least, the JavaScript part). So make sure you try to make this as safe a possible, with keys and stuff like that. Also, try to do as much logic as possible on your server, so the logic can't be changed. Only the input parameters to your API.
I hope this helped you!
Here you would need to use AJAX. jQuery has a great wrapper function called $.ajax that makes most of the process pretty simple and straightforward.
AJAX will send an asynchronous request to any file (in your case a php file) and fire a callback function with the data it receives.
(synchronous is also possible, but not recommended as it will make your application hang until the request is complete. More on why this is not recommended)
Some good reads on the subjects covered here:
http://www.sitepoint.com/ajax-jquery/
http://www.impressivewebs.com/callback-functions-javascript/
The basic technology you want to use is AJAX, which is the term for making server calls over HTTP from Javascript. You pass data to and from the server in XML (the X in AJAX) or perhaps in another encoding, such as JSON.
You'll need a dedicated PHP file on the server that will understand the data you send in the AJAX post and instead of generating HTML generates the XML/other format your Javascript will consume.
Your best bet would probably be to create a browser app that communicates with your server via AJAX, and when that is working port it to PhoneGap.
It's very easy. Just do a GET request to the PHP page and parse the result. Create a function to make it easier:
function httpGet(theUrl){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
Then, you can call it and obtain the resultant HTML code.
var url = 'http://yourpage/index.php?a=something&b=otherthing';
var page = httpGet(url);

Whats an alternative way of updating a page with new records as they are inserted into a table automatically without using jquery/ajax

I've wrote a small chat system using jquery, php, and mysql; however, I'm looking for some kind of technology that will only update a if a new record is inserted into a row. I feel like using jquery ajax calls every second to retrieve new records is really overkill and strenuous on my server.
You are looking for a Comet solution: http://en.wikipedia.org/wiki/Comet_%28programming%29
The idea, as pdr noted, is to the javascript continuously open an async request with the server. The server holds it open, but does not send anything until it determines there is something to send. The request will timeout on the javascript side after 10-20 seconds, after which it should re-open the connection.
This uses a 'subscriber' based model, by which the server will send out the chat message or what have you, to all clients which are subscribed, all at once. This saves you many database requests, as the server is the one asking for the requests, not the individual clients.
What you want is long polling. Basically, you make an XHR, and the server and PHP holdes the request open until new data is ready to be sent back.
You need to configure Apache not to timeout in this circumstances, so do some substantial research. Basically, the PHP looks like so...
set_time_limit(0);
while (TRUE) {
$db->query('SELECT `message` FROM `messages` WHERE `new` = TRUE');
if ($db) {
echo json_encode($db->results());
exit;
}
sleep(1);
}
Then, you make an XHR for this page, and it will stay open until new data is ready. Then, on the complete callback, update your page's state and make a new XHR.
This is a lot more efficient than polling for updates continually using XHR.
Make sure you do a lot of research because I believe Apache is going to think things are wrong if a PHP script hasn't stopped after 30 seconds or so. :)
There are a couple routes I know of that you can take.
Long polling. This is where the browser opens a connection to the server and does nothing until the server responds. Once the server responds or times-out (sends an empty response to the browser), a new long-polling request is made.
When going this route, you should use a server that does not rely on using a new thread for each request.
Web sockets. Again, you'll want a server that can handle requests without spawning a new thread every request. With web sockets, a connection is kept open between the client and servier, and unlike Long polling, doesn't time out. However, this isn't well-supported yet.
I highly recommend checking out http://socket.io/
The point of Ajax is that it's asynchronous. Can you not just wait at the server until there's a worthwhile response to send?
With standard HTML/CSS/JS, that's pretty much the only way since the browser can make requests of the server, not vice versa. The AJAX call shouldn't have to be very big at all. A chat system, by definition, is going to require hitting the server a lot.

I need an example of comet refresh html when database is updated!

People,
I am developing a web page that need to be refresh everytime that the data base gets an update. I already have the checkDatabaseUpdate() done in my PHP code.
But now I reaaly need some help to develop a simple comet to wait for a response, and another to check for update.
Is there anybody with any simple example to help me?
Is comet the right solution for that?
Thanks,
What you want to say is that on the database are executed querys (INSERT, UPDATE, DELETE) in the backend and you want to refresh the front page of a user when that query`s are executed ?
Hmm .. use a jQuery (looping) to "Ajax check" for database update in the frontcontroller and then refresh.
function refreshPage () {
$.load('checkModifDb.php', function(response, status) {
if .... { do the trick here - check jquery load.api }
}
});
and then use setInterval( "refreshPage()", 10000 ); to run the function every 10 seconds and
refresh only if it founds that db was modified.
I can't think of anything right now but i guess with little modification you shoul do the trick. This is how twitter.com do it.
Is comet the right solution for that?
Because of the way that PHP works (having a web server daemon process incoming requests), combining it with long-polling techniques can make for an unhappy server. Each connected user is going to hold open a connection to the web server daemon. Depending on that daemon's configuration, you may find that comet is an effective denial of service attack against your own server.
You'd probably be better off with plain old short-lived ajax polling here.

Categories