Skip to content

Instantly share code, notes, and snippets.

@fabiovalse
Last active January 4, 2016 05:39
Show Gist options
  • Select an option

  • Save fabiovalse/8576263 to your computer and use it in GitHub Desktop.

Select an option

Save fabiovalse/8576263 to your computer and use it in GitHub Desktop.
Server Sent Events based PHP Debugger
Header set Access-Control-Allow-Origin "*"

This PHP debugger uses the HTML5 Server Sent Events (SSE) technology. SSE allows to send messages from the server side, where the PHP is executed, to the client side. Thus it is possible to include send_event() operation inside PHP scripts.

Moreover on the client side the index.js script can handle in different ways the messages sent by the PHP script (sender.php). In this example three displaying method are considered:

  1. console.log;
  2. alert;
  3. text on a html div tag.

Using this approach it is possible to track and debug the execution of the PHP script just by looking at the log console of your browser.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="index.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<title>Server Sent Events based PHP Debugger</title>
</head>
<body onload="main()">
<div id="debug_message"></div>
</body>
</html>
(function() {
window.main = function() {
var log, source;
log = document.getElementById('log');
source = new EventSource('http://wafi.iit.cnr.it/asia/test/sse/sender.php');
source.onopen = function() {
return console.log('Connection established!\n');
};
// 'ping' event callback
source.addEventListener('ping', (function(e) {
var obj;
obj = JSON.parse(e.data);
// 0: end the connection with the EventSource
if (obj.e_code == 0) {
source.close();
}
// -1: debug printing on the console
else if (obj.e_code == -1) {
console.log("debug:" + obj.e_value);
}
// -2: debug with an alert
else if (obj.e_code == -2) {
alert("debug:" + obj.e_value);
}
// -3: debug printing on an html div
else if (obj.e_code == -3) {
$('#debug_message').text("debug:" + obj.e_value);
}
}), false);
return source.onerror = function(e) {
return alert('Error!');
};
};
}).call(this);
<?php
header("Content-Type: text/event-stream\n\n");
$cont = 0;
send_event(-1, "cycle starting");
while ($cont < 10) {
// Send an event to the client only by calling the "send_event" function!
send_event(-1, "iteration " . $cont);
// Wait a second
sleep(1);
$cont += 1;
}
send_event(-1, "cycle ending");
send_event(0, "");
/*
$event_code defines how the $event_value is displayed on the client.
-1: console.log
-2: alert
-3: as text in a div tag
$event_value is the text value displayed on the client.
*/
function send_event($event_code, $event_value) {
echo "event: ping\n";
echo 'data: {"e_code": "' . $event_code . '", "e_value": "' . $event_value . '"}';
echo "\n\n";
ob_flush();
flush();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment