I'm building a person to person chat, and want person A's page to refresh, loading new messages from Person B when Person B sends them. How would I send a message/data to Person A when Person B sends a message via PHP? I know I can check on Person A's page via Ajax, but constantly running a MySQL query would drastically bring down the server's speed. Any ideas?
EDIT: Using Server Sent Events, here's my script code:
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("update.php?user=<? echo $recip ?>");
source.onmessage = function(event) {
document.write(event.data);
if (event.data=="yes"){
window.location.href="/chat?with=<? echo $recip ?>";
}
};
} else {
document.getElementById('info-text').innerHTML="Hmm... looks like your browser doesn't support auto updating. Please refresh the page to check for new messages." //'
}
And here's my PHP code:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$user=$_GET['user'];
$sql=mysql_query("SELECT * FROM chatmsg WHERE sender='$myusername' AND receiver='$recip' OR sender='$recip' AND receiver='$myusername'");
$newrows=mysql_num_rows($sql);
if ($newrows!=$_SESSION['chat'.$user]) {
echo "data: yes";
flush();
}
else {
echo "data: no";
flush();
The problem is, nothing is happening when there's a new row in MySQL.
I found the solution, everyone. I still used the Server Sent Events, but made some changes and found the error. Here's the final working code:
PHP:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header("Access-Control-Allow-Origin: *");
$user=$_GET['user'];
$sql=mysql_query("SELECT * FROM chatmsg WHERE sender='$myusername' AND receiver='$user' OR sender='$user' AND receiver='$myusername'");
$newrows=mysql_num_rows($sql);
if ($newrows!==$_SESSION['chat'.$user]) {
$msg="yes";
}
else {
$msg="no";
}
echo "data: {$msg}\n\n";
flush();
sleep(10);
(sleep is to save server resources).
JS:
var source = new EventSource('update.php?user=<? echo $recip ?>');
source.onmessage = function(e) {
if (e.data=="yes") {
window.location.href="viewchat.php?viewer=<? echo $viewer ?>&recip=<? echo $recip ?>";
}
}
Related
Please excuse me, I am quite new with backend development.
What I try to accomplish is pretty straight forward. I want to send a POST request to my server. As an example; www.domain.com/api.php?id=foo
And with that value update my SSE with that parameter. But I can't seem to figure it out. I guess I need to store that value somehow in a database or a text file? Preferably in a text file for simplicity.
What I have now:
HTML file:
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
PHP file:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$test = "One";
echo "data: Page: {$test}\n\n";
flush();
?>
So my question is: How do I change the value of the variable 'test' from a POST request so that the SSE is updated?
It works perfectly now, if I change the value in the PHP file it starts spitting that out in the HTML. But how do I change that value with something external like a POST call?
Thank you! And let me know if I need to clarify.
Okay, so I managed to make it work with a SQL database. :) This is my solution:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// QUERY THE DATABASE FOR CURRENT PAGE NUMBER
$db = new mysqli($host, $username, $password, $database_name); // connect to the DB
$query = $db->prepare("SELECT number FROM page WHERE itemId=1"); // prepate a query
$query->execute(); // actually perform the query
$result = $query->get_result(); // retrieve the result so it can be used inside PHP
$r = $result->fetch_array(MYSQLI_ASSOC); // bind the data from the first result row to $r
// ECHO SERVER SENT EVENT
$pageNumber = $r['number'];
echo "data: Page: {$pageNumber}\n\n";
flush();
// UPDATE QUERY BASED ON GET PARAMATERS
$siteURL = $_GET['page'];
$updateQuery = $db->prepare("UPDATE `page` SET `number` = '$siteURL' WHERE `page`.`itemId` = 1;");
$updateQuery->execute();
?>
I'm working on a one-way messaging system using server-sent events. I have a file (server.html) which sends the contents of a textarea to a PHP file (handler.php).
function sendSubtitle(val) {
var xhr = new XMLHttpRequest();
var url = "handler.php";
var postdata = "s=" + val;
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(postdata);
//alert(val);
}
This works (alert(val) displays the text in the textarea).
My handler.php code looks like this:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$stringData = $_POST['s'];
echo "data: Data is {$stringData}\n\n";
flush();
And the relevant part of my SSE receiver file (client.html) is as follows:
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("handler.php");
source.onmessage = function(event) {
var textarea = document.getElementById('subtitles');
textarea.value += event.data + "<br>";
textarea.scrollTop = textarea.scrollHeight;
};
} else {
document.getElementById("subtitles").value = "Server-sent events not supported.";
}
The problem is that client.html only displays "data: Data is", so the text from server.html is getting lost somewhere along the way. I imagine it's the PHP code that's falling over, but I can't work out what's wrong. If anyone can help, I'd appreciate it.
EDIT
I chose to use SSE as opposed to websockets as I only need one-way communication: server.html should push the contents of its textarea to client.html whenever it changes. All the examples of SSE that I've looked at (and I've looked at a lot!) send "automatic" time-based data. I haven't seen any that use real-time user input. So perhaps I should clarify my original question and ask, "How can I use SSE to update a DIV (or whatever) in web page B whenever the user types in a textarea in web page A?"
UPDATE
I've narrowed the issue down to the while loop in the PHP file and have therefore asked a new question: Server-side PHP event page not loading when using while loop
Assuming you want to send a value from server.html and a value at client.html will be automatically updated...
You will need to store the new value somewhere because multiple instances of a script do not share variables just like that. This new value can be stored in a file, database or as a session variable, etc.
Steps:
Send new value to phpScript1 with clientScript1.
Store new value with phpScript1.
Connect clientScript2 to phpScript2.
Send stored value to clientScript2 if it is changed.
Getting the new value 'on the fly' means phpScript2 must loop execution and send a message to clientScript2 whenever the value has been changed by clientScript1.
Of course there are more and different approaches to achieve the same results.
Below there's some code from a scratchpad I've used in previous project.
Most parts come from a class (which is in development) so I had to adopt quite a lot of code. Also I've tried to fit it into your existing code.
Hopefully I didn't introduce any errors.
Do note I did not take any validation of your value into account! Also the code isn't debugged or optimized, so it's not ready for production.
Client side (send new value, e.g. your code):
function sendSubtitle(val) {
var xhr = new XMLHttpRequest();
var url = "handler.php";
var postdata = "s=" + val;
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(postdata);
//alert(val);
}
Server side (store new value):
<?php
session_start();
$_SESSION['s'] = $_POST['s'];
Client side (get new value):
//Check for SSE support at client side.
if (!!window.EventSource) {
var es = new EventSource("SSE_server.php");
} else {
console.log("SSE is not supported by your client");
//You could fallback on XHR requests.
}
//Define eventhandler for opening connection.
es.addEventListener('open', function(e) {
console.log("Connection opened!");
}, false);
//Define evenhandler for failing SSE request.
es.addEventListener('error', function(event) {
/*
* readyState defines the connection status:
* 0 = CONNECTING: Connecting
* 1 = OPEN: Open
* 2 = CLOSED: Closed
*/
if (es.readyState == EventSource.CLOSED) {
// Connection was closed.
} else {
es.close(); //Close to prevent a reconnection.
console.log("EventSource failed.");
}
});
//Define evenhandler for any response recieved.
es.addEventListener('message', function(event) {
console.log('Response recieved: ' + event.data);
}, false);
// Or define a listener for named event: event1
es.addEventListener('event1', function(event) {
var response = JSON.parse(event.data);
var textarea = document.getElementById("subtitles");
textarea.value += response + "<br>";
textarea.scrollTop = textarea.scrollHeight;
});
Server side (send new value):
<?php
$id = 0;
$event = 'event1';
$oldValue = null;
session_start();
//Validate the clients request headers.
if (headers_sent($file, $line)) {
header("HTTP/1.1 400 Bad Request");
exit('Headers already sent in %s at line %d, cannot send data to client correctly.');
}
if (isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] != 'text/event-stream') {
header("HTTP/1.1 400 Bad Request");
exit('The client does not accept the correct response format.');
}
//Disable time limit
#set_time_limit(0);
//Initialize the output buffer
if(function_exists('apache_setenv')){
#apache_setenv('no-gzip', 1);
}
#ini_set('zlib.output_compression', 0);
#ini_set('implicit_flush', 1);
while (ob_get_level() != 0) {
ob_end_flush();
}
ob_implicit_flush(1);
ob_start();
//Send the proper headers
header('Content-Type: text/event-stream; charset=UTF-8');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no'); // Disables FastCGI Buffering on Nginx
//Record start time
$start = time();
//Keep the script running
while(true){
if((time() - $start) % 300 == 0){
//Send a random message every 300ms to keep the connection alive.
echo ': ' . sha1( mt_rand() ) . "\n\n";
}
//If a new value hasn't been sent yet, set it to default.
session_start();
if (!array_key_exists('s', $_SESSION)) {
$_SESSION['s'] = null;
}
//Check if value has been changed.
if ($oldValue !== $_SESSION['s']) {
//Value is changed
$oldValue = $_SESSION['s'];
echo 'id: ' . $id++ . PHP_EOL; //Id of message
echo 'event: ' . $event . PHP_EOL; //Event Name to trigger the client side eventhandler
echo 'retry: 5000' . PHP_EOL; //Define custom reconnection time. (Default to 3000ms when not specified)
echo 'data: ' . json_encode($_SESSION['s']) . PHP_EOL; //Data to send to client side eventhandler
//Note: When sending html, you might need to encode with flags: JSON_HEX_QUOT | JSON_HEX_TAG
echo PHP_EOL;
//Send Data in the output buffer buffer to client.
#ob_flush();
#flush();
}
//Close session to release the lock
session_write_close();
if ( connection_aborted() ) {
//Connection is aborted at client side.
break;
}
if((time() - $start) > 600) {
//break if the time exceeds the limit of 600ms.
//Client will retry to open the connection and start this script again.
//The limit should be larger than the time needed by the script for a single loop.
break;
}
//Sleep for reducing processor load.
usleep(500000);
}
You called handler.php first time in the server.html and again in client.html. Both are different processes. The variable state won't be retained in the web server. You need to store it somewhere if you want that value in another PHP process. May be you can use sessions or database.
While using sessions you can store the values in two files like:
<?php
//server.php
session_start();
$_SESSION['s'] = $_POST['s'];
And in client.php
<?php
//client.php
session_start();
echo "data: Data is ".$_SESSION['s']."\n\n";
Trying to create a small notification system. When user fills out the profile then his verification status is set to 1 in database and then I would like to show a notification once that "hey you are now verified". Been searching a lot on the internet, but nothing has helped me to reach my goal. If the status is 1 in database I get the Event: verification_ok in the test.php but if it is 0 I get Maximum execution time of 120 seconds exceeded. Also I don't see any response in my client side code.
This is the server side code (test.php).
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header("Connection: Keep-alive");
require_once $_SERVER['DOCUMENT_ROOT'].'/PHP/scripts/no_session_redirect.php';
$key = true;
$ver = $user_home->runQuery("SELECT verification_status FROM verification WHERE user_id=:user_id");
$ver->execute(array(":user_id"=>$user_id));
$status = $ver->fetch(PDO::FETCH_ASSOC);
while($key){
if($status["verification_status"] == 1){
pushNotification($status["verification_status"]);
$key = false;
}else{
$status["verification_status"];
sleep(10);
}
}
function pushNotification() {
echo "Event: verification_ok\n";
}
And here is the client side code:
$(document).ready(function() {
if (typeof(EventSource) !== "undefined") {
// Yes! Server-sent events support!
var source = new EventSource("test.php");
source.addEventListener("verification_ok", function(e) {
console.log(e.data);
}, false);
source.addEventListener("open", function(e) {
}, false);
source.addEventListener("error", function(e) {
if (e.readyState == EventSource.CLOSED) {
console.log("Error - connection was lost.");
}
}, false);
} else {
// Sorry! No server-sent events support..
}
});
As soon as I entered a site, my browser (chrome) downloaded this script. It's not obfuscated and not too long, and I think it's harmless, but I don't know PHP so i'm not sure. The file was called csync.php.
Chrome made it seem like this was the only file downloaded. Is it possible this is not true?
Could someone shed some light on what this is doing?
<?php
require_once("config/config.php");
require_function("util/StaticFunctions.php");
require_function("service/ServiceFactory.php");
require_function("bo/BoFactory.php");
require_function("data/DataFactory.php");
require_function("util/UtilFactory.php");
require_function("data/AkamaiLoggingService.php");
include 'config/setup/config-setup-skenzo.php';
include 'config/skenzo_request_variables.php';
header('P3P:CP="NON DSP COR NID CUR ADMa DEVo TAI PSA PSDo HIS OUR BUS COM NAV INT STA"');
header('Content-type: text/html');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: -1');
$visitorInfo = BoFactory::getVisitorInfo();
$vsid = $visitorInfo->getVisitorId();
$dataNames = VisitorInfo::$VSID_DATA_NAMES;
$mName = BoFactory::getInboundHttpRequest()->getSanitizedValueOfParam('type');
$mValue = BoFactory::getInboundHttpRequest()->getSanitizedValueOfParam('ovsid');
$vsCk = VISITOR_ID;
$vsDaCk = VISITOR_DATA;
$sepVal = VisitorInfo::$VALUE_SEP;
$sepTime = VisitorInfo::$TIME_SEP;
$vsDaTime = VisitorInfo::$VSID_DATA_TIME;
echo '<html> <head></head> <body> <script type="text/javascript" >';
$vsyncConf = array (
"vsCk" => $vsCk,
"vsDaCk" => $vsDaCk,
"sepVal" => $sepVal,
"sepTime" => $sepTime,
"vsDaTime" => $vsDaTime
);
echo "var vsyncConfig = " . json_encode($vsyncConf) . ";\n";
include(SKENZO_MEDIA_DIR. '/js/util/C2/modules/mnvdata.js');
echo '</script>';
echo "</body></html>";
if(AKAMAI_LOG_POSTBACK == $_SERVER['SERVER_NAME'])
{
define('AKAMAI_BULK_LOGGING', TRUE);
define('TEST_ENGINE_FROM_SERVING', '1');
try
{
$akLogService = new AkamaiLoggingService();
$akLogService->handleAkamaiBulkData();
echo '<!--var logged = 1;-->';
}
catch(Exception $e)
{
error("RTBLOG AKAMAI ERROR: " , $e , LOG_ALERT);
echo '<!--var logged = 0;-->';
}
}
else
{
if(AKAMAI_LOG_ORIGIN == $_SERVER['SERVER_NAME'])
{
echo '<!--var logged = 1;-->';
}
else
{
define('AKAMAI_BULK_LOGGING', TRUE);
define('TEST_ENGINE_FROM_SERVING', '1');
try
{
$akLogService = new AkamaiLoggingService();
$akLogService->handleGetRequests();
echo '<!--var logged = 1;-->';
}
catch(Exception $e)
{
error("RTBLOG AKAMAI ERROR: " , $e , LOG_ALERT);
echo '<!--var logged = 0;-->';
}
}
}
?>
The server you're visiting is poorly configured. As a result, instead of executing the PHP, the server sent it to your browser. Browsers don't execute PHP so you're safe.
If you care about the site you were visiting, the nice thing to do would be to contact support and refer it to this post.
A similarly named csync.php file has been reported in a couple of places online over the last couple of days. This, along with its reference to AKAMAI (a huge content delivery network), suggests that the mis-configured server isn't the 1st party site you were actually on, but a 3rd-party server that the site, along with many others, relies on.
File's apparent source: http://qsearch.media.net/csync.php
Similar reports (Google): https://encrypted.google.com/search?q=csync.php+download
I also saw this file drop into my downloads. The source is qsearch.media.net. If you visit media.net, you'll see it is part of the internet advertisement ecosystem. It's likely that there is a bug in one of their scripts. Sites using media.net's service then incidentally cause your computer to download this php file.
This is absolutely not server error of any websites, it is because my browser also download this script from multiple sites,one of them are from speedtest.net, i don't know what's hack is going on.
i'm building in php a reservation website with a schedule. I'm looking to have real time updates for my users in a efficient way. I found Ajax but I dont want the client to ask the server about updates but the server to send to the client the updated schedule when somebody edited the schedule.
I found that maybe the HTML5 Server Sent Events is what I need. So I tried a simple test page that retreive update via SSE.
demo.html
<!DOCTYPE html>
<html>
<body>
<h1>SSE Output</h1>
<div id="result"></div>
<h1>Debug Console</h1>
<div id="status"></div>
<script>
//SSE si compatible
if(typeof(EventSource)!=="undefined")
{
var i = 1;
var source=new EventSource("demo_sse.php?ver=2");
//Lorsque le serveur envoie un message
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + " #" + i + "<br />";
i++;
}
//EventListener
source.addEventListener('message', function(e)
{
console.log(e.data);
//document.getElementById("status").innerHTML+= "Message Recevied<br />";
}, false);
source.addEventListener('open', function(e)
{
// Connection was opened.
document.getElementById("status").innerHTML+= "Connection #" + i + " opened<br />";
}, false);
source.addEventListener('error', function(e)
{
if (e.readyState == EventSource.CLOSED)
{
// Connection was closed.
document.getElementById("status").innerHTML+= "Connection closed<br />";
}
}, false);
//Validation de l'origine du serveur
if (event.origin != 'https://mydomain.com')
{
alert('Looks like the Origin of the EventSource (the schedule\'s live update service) wasn\'t coming from our secure server!');
//return;
}
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
demo_see.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$ver = 2;
$time = date("H:i:s");
if ($ver != $_GET["ver"])
{
echo "data: Page updated at: {$time}\n\n";
flush();
}
?>
The problem is that each like 3 seconds there's a connection opened whatever if the version is matching or not so I think it's the client that ask the server and not the server asking the client. What I would like is to keep a open connection between the client and the server so the server can send changes when there's any update made on the schedule.
Any tips would be appreciated!
Thanks
The browser is reconnecting every 3 seconds because your server code isn't keeping the connection open. It sends the time once then ends. Try something more like this:
while (true) {
echo "data: Page updated at: {$time}\n\n";
flush();
sleep(1);
}