Related
I 'm writing a PHP code to be executed under apache (unfortunately under window OS by using xampp PHP 7.2.x). The PHP script should call an octave in an interactive way in order to be able to execute more commands in sequence without creating for each one a dedicated octave process.
here below an PHP script example.
I have a problem with the interactive working mode; I mean, I'm able to execute an octave script and have back the result but I'm not able to send several octave commands in sequence.
<?php
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to, you can specify a file as well
);
$octave = 'C:\Octave\Octave-4.4.0\bin\octave-cli-4.4.0 ';
$cmd = $octave . ' --no-gui -i -q --eval disp(10)';
$process = proc_open($cmd, $descriptorspec, $pipes);
if (!is_resource($process)) {
die("PROCESS CREATION ERROR CMD: $cmd");
}
$str = "eval('disp(20)');\r\n" . chr(13);
if(fwrite($pipes[0],$str) === false){
die("fwrite ERROR");
}
$str = stream_get_contents($pipes[1]);
if($str === false){
die("stream_get_contents ERROR");
}else{
echo $str;
}
fclose($pipes[0]);
fclose($pipes[1]);
$return_value = proc_close($process);
echo "command returned $return_value\n";
?>
In this case, the output is: 10 commands returned 0
Instead if define $cmd = $octave . ' --no-gui -i -q';
The script is blocked waiting for a returning charter to the stream_get_contents. Same result using fgets.
My understanding is that the fwrite command is not correctly received by an octave and so it doesn't print back the result (even if the fwrite doesn't return any error). Maybe the problem is due to the code to be sent as carriage return in order to tell to octave to execute the code. Moreover, it is not clear, if I should use the eval function or just write the command. However, in all tries done nothing is changed.
Any ideas?
Here below the code review, working if can be useful.
I have also created a dedicated class (octave_stream) in order to provide an interface that permits, for instance, an html pages to start a dedicated octave process ondemand (using a SSE communication) and then send one by one commands as ajax request. The sw will close the octave process whenever the user leave the page or after an unused time.
here below the whole code based on the following 4 files: octave.php, octave_sse.php, octave_com.php.
octave.php
<?php
class octave {
private $pipes = null;
private $process = null;
private $add_semicolon = false;
private $debug = false;
private $print = false;
function __destruct() {
$this->close_octave();
}
public function close_octave(){
if ($this->pipes !== null){
fclose($this->pipes[0]);
fclose($this->pipes[1]);
$return_value = proc_close($this->process);
if($this->debug){ echo "command returned $return_value<br>";}
return $return_value;
}
return false;
}
public function open_octave(){
$dir = sys_get_temp_dir();
$error_file_name = tempnam($dir, "npt");
$descriptorspec = array(
0 => array("pipe", "rb"), // stdin is a pipe that the child will read from
1 => array("pipe", "wb"), // stdout is a pipe that the child will write to
2 => array("file", $error_file_name,"a") // stderr:: you HAVE TO specify a file
);
$octave = 'C:\Octave\Octave-4.4.0\bin\octave-cli-4.4.0 ';
$cmd = $octave . ' --no-gui -i -q';
$pipes = array();
$this->process = proc_open($cmd, $descriptorspec, $pipes);
if (!is_resource($this->process)) {
echo "PROCESS CREATION ERROR CMD: $cmd";
return false;
}
if (count($pipes) == 0){
echo 'pipes: '; var_dump($pipes); echo '<br>';
echo "PROCESS CREATION ERROR CMD: $cmd";
return false;
}
//stream_set_blocking($pipes[1],false); // doesn't work on STDIN / OUT
$this->pipes = $pipes;
$cmd_id = 0;
$this->read($cmd_id);
return true;
} //end open_octave
private function raw_read(){
$str = fread($this->pipes[1],8192);
if($str === false){
echo '<br>'. __FUNCTION__ . ' fgets ERROR for CMD: ' . htmlentities($cmd);
return false;
}
//echo "READ: $str<br>";
return $str;
} //end read
private function read(&$cmd_num){
$result = '';
$string = $this->raw_read();
if($this->debug){echo '<br>' . __FUNCTION__ . ' RAW_READ1: ' . $string; }
if($string[0] == '>'){
//special case, multiple line statement
if($this->debug){echo '<br>' . __FUNCTION__ . ' multiple line statement.' ; }
$cmd_num = -1;
return '';
}
$tok = strtok($string, "octave:");
while (($tok === false) || ($tok == $string)) {
//the response do not conatin the promt; therefore, other rows are coming, read them as well and concatenate to the current response
$result .= $string;
usleep(100);
$string = $this->raw_read();
if($this->debug){echo '<br>' . __FUNCTION__ . ' RAW_READ NEXT: ' . $string; }
$tok = strtok($string, "octave:");
}
$cmd_num = -1;
//in this case string include the promt; nothing more to be read. tok is the string without the "ocatve:" but you still have the 'num>' to be removed.
$allTheRest = strtok( '' );
if(($allTheRest === false) || ($allTheRest == '')){
//tok has the promt rest
list($cmd_num) = sscanf($tok,'%u>');
}else{
$result .= $tok;
list($cmd_num) = sscanf($allTheRest,'ctave:%u>');
}
if($this->debug){echo '<br>' . __FUNCTION__ . " RAW_READ TOK: '$tok' STRING: '$string' RESULT: '$result' allTheRest: '$allTheRest' cmd_num: $cmd_num ## "; }
return $result;
}
//return the command answer removing the promt. Therefore, in case no retrun message command an empty string is given
public function octave_cmd($cmd,&$cmd_num){
if($this->add_semicolon){
$last_chr = strlen($cmd) - 1;
if(substr($cmd, $last_chr, 1) != ';'){
$cmd = $cmd . ';'; // adding ; at the input command required by octave
}
}
//echo "$cmd<br>";exit(0);
$cmd = $cmd . PHP_EOL ;// "\r\n"
if(fwrite($this->pipes[0],$cmd) === false){
echo '<br>'. __FUNCTION__ . ' fwrite ERROR for CMD: ' . htmlentities($cmd);
return false;
}
//usleep(100); // needed when more output row are given ... without this you read before the progam write the next row ... and you lost it ... a nice solution anyway should be to read again unil you find the promt that is always the latest given.
$ret = $this->read($cmd_num);
if($this->print){
echo "<br>COMMAND # $cmd_num: " .htmlentities($cmd) . (($ret != '')?(' RESULT: ' . nl2br(htmlentities($ret))):'') . ' END<br>';
}
return $ret;
}
public function print_cmd($cmd){
$cmd_id = 0;
$ret = $this->octave_cmd($cmd,$cmd_id);
echo "<br>COMMAND # $cmd_id: " .htmlentities($cmd) . (($ret != '')?(' RESULT: ' . nl2br(htmlentities($ret))):'') . ' END<br>';
}
}
class octave_stream {
private $address = 'tcp://127.0.0.1';
private $port = 5454;
private $errno = 0;
private $errstr = '';
private $server_istance = false;
private $sse = false;
/*This function start octave process, open a tcp connection and waits for incoming commands.
(to send the commands use the func. send_cmd)
Each command received is forwared to octave and the ocatve answer is forwared to who sent the command.
To stop the server a special command has to be sent. The caller has to use the stop_server()
*/
public function create_server($accept_max_retray = 30){
$this->server_istance = true; // first command to be done
$available_port = $this->find_usable_listening_port($this->port);
if($available_port === false){
$this->server_log('NOT FOUND AN AVAILABLE PORT TO START THE LISTENING SERVER');
return false;
}else{
$this->port = $available_port;
}
$oct_obj = new octave();
if(!$oct_obj->open_octave()){
return false;
}
$this->server_log('OCTAVE PROCESS STARTED');
$cmd_id = 0;
$server_socket_address = 'tcp://127.0.0.1:' . $this->port;
$socket = stream_socket_server($server_socket_address, $errno, $errstr);
if (!$socket) {
$this->errstr = "$errstr ($errno)<br />\n";
$this->errno = $errno;
$oct_obj->close_octave();
$this->server_log("<b>LISTENING SOCKET CREATION ERROR: $this->errstr</b>");
return false;
}
$exit = false;
$this->server_log("LISTENING SOCKET CREATED: $server_socket_address DEFAULT SOCKET TIMEOUT:" . ini_get("default_socket_timeout"));
$this->server_log($server_socket_address,'server_ready'); // dedicated event type sent, html page has a dedicated event listener on it
$accept_retray = -1;
$conn_id = 0;
do{
$accept_retray += 1;
while ($conn = stream_socket_accept($socket)) {
$this->server_log("LISTENING SOCKET CONNECTION ACCEPTED: $conn_id");
$accept_retray = -1;
//cmd: received octave command request to be sent to octave
$cmd = '';
$cmd = fread($conn,8192);
if($cmd === false){
$this->server_log( __FUNCTION__ . "[$conn_id] fread ERROR for CMD: " . htmlentities($cmd));
return false;
}
$this->server_log("[$conn_id] RECEIVED RAW COMMAND: $cmd");
if(strpos($cmd, '#exit#') !== false){
//special command EXIT
$this->server_log("[$conn_id] RECEIVED EXIT COMMAND.");
fwrite($conn,self::prefix($conn_id) . 'RECEIVED EXIT COMMAND.'); // you need always to send an answer to the calling (it is waiting on read it
$exit = true;
}else if (strpos($cmd, '#loopback:') !== false) {
//special command LOOPBACK
$this->server_log("[$conn_id] RECEIVED LOOPBACK COMMAND: $cmd");
fwrite($conn,self::prefix($conn_id) . $cmd); // you need always to send an answer to the calling (it is waiting on read it
} else {
//OCATVE COMMAND
$this->server_log("[$conn_id] RECEIVED COMMAND FOR OCTAVE: $cmd");
$cmd_id = 0;
$ret = $oct_obj->octave_cmd($cmd,$cmd_id);
$this->server_log("[$conn_id] COMMAND # $cmd_id: " .htmlentities($cmd) . (($ret != '')?(' RESULT: ' . nl2br(htmlentities($ret))):'') . ' END<br>');
fwrite($conn,self::prefix($conn_id) . 'RESULT:'. $ret);
$this->server_log("[$conn_id] SENT ANSWER: RESULT:". $ret);
}
fclose($conn);
$this->server_log("[$conn_id] CLOSE CONNECTION");
$conn_id++;
if($exit) break;
}
if($exit) break;
//note, calling the server_log func here you are testing the socket between this script and the html pages. If the sse connection is no more working, the PHP engine will close this script.
$this->server_log("LISTENING SOCKET CONNECTION TIMEOUT RETRAY: $accept_retray MAX_RETRAY: $accept_max_retray");
}while($accept_retray < $accept_max_retray);
$this->server_log($server_socket_address,'server_stopped'); // dedicated event type sent
fclose($socket);
$this->server_log('SOCKET CLOSED.');
unset($oct_obj);
$this->server_log('OCTAVE PROCESS STOPPED.');
return true;
} // end start_server
private static function prefix($conn_id){
return "[$conn_id] [" . date('n/j/Y g:i:s a') .'] ';
}
//return the ocatve command answer to be encoded e.g. json to be delivered to the http page or false
public function send_cmd($cmd){
if($this->server_istance){
$this->errstr = '<br>'. __FUNCTION__ . ' SERVER ISTANCE.';
return false;
}
$ret = '';
$fp = stream_socket_client($this->address . ':' .$this->port , $errno, $errstr, 30);
if ($fp === false) {
$this->errstr = "$errstr ($errno)<br />\n";
$this->errno = $errno;
return false;
} else {
//fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
fwrite($fp, $cmd);
while (!feof($fp)) {
$ret .= fgets($fp, 1024);
}
fclose($fp);
}
return $ret;
} // end send_cmd
//return false or the server answer
public function stop_server(){
if($this->server_istance){
$this->errstr = '<br>'. __FUNCTION__ . ' SERVER ISTANCE.';
$this->errno = 0;
return false;
}
return $this->send_cmd('#exit#');
} //
//return false or the server answer
public function loopback_msg($msg){
if($this->server_istance){
$this->errstr = '<br>'. __FUNCTION__ . ' SERVER ISTANCE.';
$this->errno = 0;
return false;
}
return $this->send_cmd('#loopback:' . $msg);
}
public function get_errstr(&$errno){
$ret = $this->errstr;
$this->errstr = '';
$errno = $this->errno;
$this->errno = 0;
return $ret;
}
//$ip_name: IP or dns name
public function set_address_connection($ip_name,$port){
$this->address = 'tcp://' . $ip_name ;
$this->port = $port;
}
//str can be encoded as json if you need to transfert more data field.
//see: https://www.html5rocks.com/en/tutorials/eventsource/basics/
private function server_log($str,$event_name = ''){
$msg = '<br>[' . date('n/j/Y g:i:s a') .'] '. $str ;
if($this->sse){
if($event_name != ''){
echo "event: $event_name" . PHP_EOL;
echo "data: $str" . PHP_EOL;
}else{
echo "data: $msg" . PHP_EOL;
}
echo PHP_EOL;
}else{
echo $msg;
}
ob_flush();
flush();
}
public function set_sse($sse){
$this->sse = $sse;
}
private function check_server_running_on_port($port,&$ret_errstr,&$errno){
if(!$this->server_istance){
$ret_errstr = '<br>'. __FUNCTION__ . ' REQUIRED SERVER ISTANCE.';
$errno = 0;
return false;
}
$ret_errstr ='';
$errno = 0;
$msg = __FUNCTION__ . ' PORT CHECK: ' . $port;
$cmd = '#loopback:' . $msg; // you cannot change it, is the defined loopback command
$fp = stream_socket_client($this->address . ':' .$port , $errno, $errstr, 30);
if ($fp === false) {
$ret_errstr = "$errstr ($errno)<br />\n";
return false;
}
fwrite($fp, $cmd);
while (!feof($fp)) {
$ret .= fgets($fp, 1024);
}
fclose($fp);
return true;
}
private function find_usable_listening_port($start_port){
if(!$this->server_istance){
$this->errstr = '<br>'. __FUNCTION__ . ' REQUIRED SERVER ISTANCE.';
$this->errno = 0;
return false;
}
$ret_errstr ='';
$errno = 0;
$max_port = $start_port +10;
$port = $start_port;
do{
//ret = true server running, so I need to find another unused port
$ret = $this->check_server_running_on_port($port,$ret_errstr,$errno);
if($ret){
$this->server_log("CHECK USABLE LISTENING PORT: PORT=$port ALREADY USED.");
}else{
$this->server_log("CHECK USABLE LISTENING PORT: PORT=$port NOT USED. GIVEN ERROR: $ret_errstr" );
return $port;
}
$port++;
if($port > $max_port) return false;
}while($ret);
return false;
}
} // end class
?>
octave_sse.php
<?php
/* this page should be called by the web page as sse
this page calling the create_server func start the octave process and the communication server as well.
The function return only when the exit command is received over the server channel created.
Then the page has to send a polling to the web page to test the presence of the page itself.
*/
function sendMsg($sse,$msg) {
if($sse){
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
}else{
echo $msg;
}
ob_flush();
flush();
}
$sse = false;
if(isset($_GET['sse'])){
if($_GET['sse'] > 0){
$sse = true;
}
}
if($sse){
header('Content-Type: text/event-stream');
}else{
header( 'Content-type: text/html; charset=utf-8' );
}
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
require 'octave.php';
set_time_limit(4000);
$oct_server_obj = new octave_stream();
if($sse){
$oct_server_obj->set_sse(true);
}
sendMsg($sse,'<br>[' . date('n/j/Y g:i:s a') .'] CALLING create_server.<br>');
$ret = $oct_server_obj->create_server();
sendMsg($sse,'<br>[' . date('n/j/Y g:i:s a') .'] create_server EXIT. return: '. (($ret)?'TRUE':'FALSE').'<br>');
//you are here only at the end when the web page send the exit command to the created server
do{
sleep(2);
sendMsg($sse,'<br>[' . date('n/j/Y g:i:s a') .'] create_server PING<br>');
}while(true);
?>
octave_com.php
<?php
/*
This page is called using a json post request from web page.
Each request has a octave command. special param is to terminate the server.
*/
/** Error reporting: this is not used since you are using myErrorHandler */
if($_SERVER['SERVER_NAME'] == "localhost"){ // my PC
error_reporting(E_ALL);
}else{
error_reporting(E_ERROR | E_PARSE);
}
//http://php.net/manual/it/errorfunc.configuration.php#ini.display-errors
/* The errors are redirect over the stderr and not over the stdout.
In this way, you have to properly send the error using json without using the set_error_handler.
ini_set('display_errors','Off');
//ini_set('display_errors','On');
*/
function myErrorHandler ($errno, $errstr, $errfile, $errline) {
if (0 === error_reporting()) { return false;}
$errorType = array (
E_ERROR => 'ERROR',
E_WARNING => 'WARNING',
E_PARSE => 'PARSING ERROR',
E_NOTICE => 'NOTICE',
E_CORE_ERROR => 'CORE ERROR',
E_CORE_WARNING => 'CORE WARNING',
E_COMPILE_ERROR => 'COMPILE ERROR',
E_COMPILE_WARNING => 'COMPILE WARNING',
E_USER_ERROR => 'USER ERROR',
E_USER_WARNING => 'USER WARNING',
E_USER_NOTICE => 'USER NOTICE',
E_STRICT => 'STRICT NOTICE',
E_RECOVERABLE_ERROR => 'RECOVERABLE ERROR');
// create error message
if (array_key_exists($errno, $errorType)) {
$err = $errorType[$errno];
} else {
$err = 'CAUGHT EXCEPTION';
}
if($_SERVER['SERVER_NAME'] != "localhost"){ // not my PC
if (!($errorType == E_ERROR ) || ($errorType == E_PARSE ))
return;
}
$str_err = "$err($errno) <br> in line: " .$errline. " of file: " .$errfile . " <br> PHP: " . PHP_VERSION . " (". PHP_OS .")<br> $errstr";
terminate($str_err);
} // end myErrorHandler
// configura il gestore dell'errore definito dall'utente
$old_error_handler = set_error_handler("myErrorHandler");
// functions
function terminate($str_err, $txt=false){
if($txt){
die($str_err);
}
header("Content-Type: application/json;charset=utf-8");
echo json_encode(array("result"=>"false","error"=>$str_err));
exit(0);
} // end terminate
require 'octave.php';
if(isset($_POST['send_loopback'])){
if(!isset($_POST['message'])){
terminate("message not present!");
}else{
$message = $_POST['message'];
}
$address = '';
$ip='';
$port = 0;
if(isset($_POST['address'])){
$address = $_POST['address'];
$pos = strrpos($address,':');
$ip = substr($address,6,$pos-6);
$port = substr($address,$pos+1);
}
$oct_server_obj = new octave_stream();
//it is supposed to have the server already running ready to manage the sent messages here below
//echo '<br>[' . date('n/j/Y g:i:s a') .'] SEND THE LOOPBACK MESSAGE.<br>';
if($ip != '' and is_numeric($port)){
$oct_server_obj->set_address_connection($ip,$port);
}
$msg = $oct_server_obj->loopback_msg($message);
if($msg === false){
$errno = 0;
terminate($oct_server_obj->get_errstr($errno));
}
echo json_encode(array('result' => 'true', 'error' => '', 'loopback_msg' => $msg)) ;
exit(0);
} // end send_loopback
if(isset($_POST['send_octave_msg'])){
if(!isset($_POST['message'])){
terminate("message not present!");
}else{
$message = $_POST['message'];
}
$address = '';
$ip='';
$port = 0;
if(isset($_POST['address'])){
$address = $_POST['address'];
$pos = strrpos($address,':');
$ip = substr($address,6,$pos-6);
$port = substr($address,$pos+1);
}
$oct_server_obj = new octave_stream();
//it is supposed to have the server already running ready to manage the sent messages here below
//echo '<br>[' . date('n/j/Y g:i:s a') .'] SEND THE LOOPBACK MESSAGE.<br>';
if($ip != '' and is_numeric($port)){
$oct_server_obj->set_address_connection($ip,$port);
}
$msg = $oct_server_obj->send_cmd($message);
if($msg === false){
$errno = 0;
terminate($oct_server_obj->get_errstr($errno));
}
$pos = strpos($msg,'RESULT:');
$ret = trim(substr($msg,$pos+strlen('RESULT:')));
$ret = nl2br(htmlentities($ret));
echo json_encode(array('result' => 'true', 'error' => '', 'msg' => $msg, 'return' => $ret)) ;
exit(0);
} // end send_octave_msg
if(isset($_GET['send_exit_msg'])){
$address = '';
$ip='';
$port = 0;
if(isset($_GET['address'])){
$address = $_GET['address'];
$pos = strrpos($address,':');
$ip = substr($address,6,$pos-6);
$port = substr($address,$pos+1);
}
$oct_server_obj = new octave_stream();
//it is supposed to have the server already running ready to manage the sent messages here below
//echo '<br>[' . date('n/j/Y g:i:s a') .'] SEND THE LOOPBACK MESSAGE.<br>' . "ADDRESS: $address IP: $ip PORT: $port<br>" ;
if($ip != '' and is_numeric($port)){
$oct_server_obj->set_address_connection($ip,$port);
}
$msg = $oct_server_obj->stop_server();
if($msg === false){
$errno = 0;
terminate($oct_server_obj->get_errstr($errno));
}
echo json_encode(array('result' => 'true', 'error' => '', 'return' => $msg)) ;
exit(0);
} // end send_exit_msg
?>
The html web page to be used together with the above code.
octave_shell.html:
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="../../jquery/jqueryui/jquery-ui-1.11.3.custom/jquery-ui.css">
<link rel="stylesheet" href="../../libs/messi/messi.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../../jquery/jqueryui/jquery-ui-1.11.3.custom/jquery-ui.js"></script>
<script src="../../libs/messi/my_messi.min.js"></script>
<script src="../../libs/chosen/chosen.jquery.min.js"></script>
<title>OCTAVE SHELL</title>
</head>
<body>
<h2>OCTAVE WEB INTERFACE</h2>
<script type="text/javascript">
var server_ready = false; // true, octave process running and ready to accept commands
var sse_source; // sse_obj
var octave_close_req = false; // true when the user stop octave
var address = ''; //address on which the server is in listening for commands at server side
function clearArray(array_tbc){
array_tbc.splice(0,array_tbc.length); // set the array to empty
array_tbc.length = 0;
}
function isParamExist(paramName){
if($.inArray(paramName,Object.getOwnPropertyNames(urlParams)) > -1){
console.log("isParamExist:" + paramName + " return TRUE");
return true;
}
console.log("isParamExist:" + paramName + " return FALSE");
return false;
} //end isParamExist
function getParam(urlParams) {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
console.log(Object.getOwnPropertyNames(urlParams));
} //end getParam
function octave_close(){
octave_close_req = true;
$.getJSON('octave_com.php',
{send_exit_msg: 1,
address: address},
function(data) {
if(data.result == "true"){
$('#octave_shell').append("<p><b>"+ data.return +"</b></p>" );
}else{
//alert("Error : " + data.error);
new Messi('Error : ' + data.error, {title: 'ERROR from JSON', titleClass: 'anim error', buttons: [{id: 0, label: 'Close', val: 'X'}]});
}
}
);
} //end octave_close
function ping_server(){
var message = 'HELLO!';
$.post( "octave_com.php",
{ send_loopback: 1,
address: address,
message: message } ,
function( data ) {
if(data.result == 'true'){
var msg = data.loopback_msg;
$('#octave_shell').append("<p><b>"+ msg +"</b></p>" );
}else{
var err = data.error;
new Messi("LOOPBACK ERROR: err: " + err, {title: 'LOOPBACK MESSAGE', titleClass: 'anim warning', buttons: [{id: 0, label: 'Close', val: 'X'}]});
}
},
"json");
} //end ping_server
function send_octave_cmd(cmd){
$.post( "octave_com.php",
{ send_octave_msg: 1,
address: address,
message: cmd } ,
function( data ) {
if(data.result == 'true'){
var msg = data.return;
if(msg == '') msg = 'OK';
$('#octave_shell').append("<p>OCTAVE ANSWER: " + msg + "</p>");
console.log('OCTAVE MESSAGE: ' + data.msg);
}else{
var err = data.error;
new Messi("OCTAVE COMMAND: err: " + err, {title: 'OCTAVE COMMAND ERROR', titleClass: 'anim warning', buttons: [{id: 0, label: 'Close', val: 'X'}]});
}
},
"json");
} //end send_octave_cmd
$(function(){
if(typeof(EventSource) !== "undefined") {
sse_source = new EventSource("octave_sse.php?sse=1");
sse_source.onmessage = function(event) {
console.log('SSE MSG: ' + event.data);
document.getElementById("sse_log").innerHTML += event.data + "<br>";
};
sse_source.addEventListener('open', function(e) {
// Connection was opened.
console.log('SSE OPEN.');
document.getElementById("sse_log").innerHTML += 'SSE OPEN.' + "<br>";
}, false);
sse_source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
// Connection was closed.
server_ready = false;
console.log('SSE CLOSED.');
document.getElementById("sse_log").innerHTML += 'SSE CLOSED.' + "<br>";
}
}, false);
//user defined event types
sse_source.addEventListener('server_ready', function(e) {
// server_ready event received.
server_ready = true;
address = e.data;
console.log('SSE server_ready EVENT ADDR: ' + address);
$('#octave_status').text('SERVER READY TO ACCEPT OCTAVE COMMANDS ON: '+ address);
}, false);
sse_source.addEventListener('server_stopped', function(e) {
// server_stopped event received.
server_ready = false;
console.log('SSE server_stopped EVENT');
setTimeout(function(){ sse_source.close(); }, 3000); //close the sse connection as well, you don't need anymore.
if(!octave_close_req){
$('#octave_status').text('SERVER HAS BEEN CLOSED FOR TIMEOUT. RE-LOAD THE PAGE TO START A NEW WORKING SESSION.');
new Messi(
'OCTAVE PROCESS STOPPED FOR TIMEOUT. RE-LOAD THE PAGE TO START A NEW WORKING SESSION.',
{
title: 'OCTAVE PROCESS STOPPED',
titleClass: 'anim info',
buttons: [ {id: 0, label: 'Close', val: 'X'} ]
}
);
}else{
$('#octave_status').text('SERVER HAS BEEN CLOSED FOR USER DECISION. RE-LOAD THE PAGE TO START A NEW WORKING SESSION.');
new Messi(
'YOU HAVE CLOSED CORRECTLY THE OCTAVE PROCESS. RE-LOAD THE PAGE TO START A NEW WORKING SESSION.',
{
title: 'OCTAVE PROCESS STOPPED',
titleClass: 'anim info',
buttons: [ {id: 0, label: 'Close', val: 'X'} ]
}
);
}
}, false);
} else {
alert('NO SSE SUPPORT. Please do not use an obsolete browser!');
}
$('#close_octave_id').click(function() {
console.log('CLOSE OCTAVE REQUEST');
octave_close();
});
$('#send_ping_id').click(function() {
console.log('PING DISPATCHER SERVER REQUEST');
ping_server();
});
$('#send_octave_cmd_id').click(function() {
var cmd = $('#write_octave_cmd_id').val();
//console.log('SEND OCTAVE CMD REQUEST: ' + cmd);
$('#octave_shell').append("<p>OCTAVE: " + cmd + "</p>");
send_octave_cmd(cmd);
$('#write_octave_cmd_id').val('');
});
$('#write_octave_cmd_id').keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$('#send_octave_cmd_id').click();
return false;
}
});
//getParam(urlParams);
/*
if(!isParamExist('json_file_net_name')){
//load the NPT results
loadNPTData();
}else{
// load DESIGN results
loadJSONData();
}
*/
}); // end startup page
</script>
<div id='octave_cmd'>
<h4>Write your OCTAVE commands here, press enter or click on SEND OCTAVE CMD to execute them.<br>
<b>IMPORTANT: </b>Don't forget to terminate the commands with semicolon as per OCTAVE syntax.</h4>
<br><p>Some example commands: disp(10) just to print 10,<br>
to solve a non linear system equation writes the following commands line by line pressing enter for each row:<br>
<i>function y = test6(x)<br>
y(1) = 18.028*cosd(x(1))+10*cosd(45)-15*cosd(x(2))<br>
y(2) = 18.028*sind(x(1))+10*sind(45)-15*sind(x(2))<br>
endfunction<br>
[x, fval, info] = fsolve(#test6, [0;0]);<br>
disp(x);<br>
disp(info);</i><br>
</p><br>
</div><br>
<br><a href='#' id='close_octave_id' >CLOSE OCTAVE - CLICK WHEN YOU HAVE TERMINATED.</a><br>
<br><a href='#' id='send_ping_id' >PING DISPATCHER SERVER </a><br>
<div id='octave_status'></div>
<br><div id='octave_shell'><h4>OCTAVE SHELL:</h4><br></div><br>
<input type='text' id='write_octave_cmd_id' size="400"><br>
<a href='#' id='send_octave_cmd_id' >SEND OCTAVE CMD</a>
<br><div id='sse_log'><h4>SSE LOG:</h4><br></div><br>
</body>
</html>
I have a function inside a class, and I would like to get the result of this function, something like:
Returned dangerous functions are: dl, system
Here is my code
public final function filterFile(){
$disabled_functions = ini_get('disable_functions');
$disFunctionsNoSpace = str_replace(' ', '', $disabled_functions);
$disFunctions = explode(',', $disFunctionsNoSpace);
$this->disFunctions = $disFunctions;
// get file content of the uploaded file (renamed NOT the temporary)
$cFile = file_get_contents($this->fileDestination, FILE_USE_INCLUDE_PATH);
$found = array();
foreach($this->disFunctions as $kkeys => $vvals)
{
if(preg_match('#'.$vvals.'#i', $cFile))
{
array_push($found, $vvals);
}
} // end foreach
} // end filterFile
// calling the class
$up = new uploadFiles($filename);
$fileterringFile = $up->filterFile();
print_r($fileterringFile);
var_dump($fileterringFile);
EDIT: add 2 functions for errors:
// check if any uErrors
public final function checkErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
return true;
}
return false;
} // end checkErrors()
// print user errors
public final function printErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
echo '<ul>';
foreach($this->uErrors as $uV)
{
echo '<li>';
echo $uV;
echo '</li>';
}
echo '</ul>';
}
} // end printErrors()
Thanks in advance
at the end of end filterFile, add:
return 'Returned dangerous functions are: '.implode(',',$found);
I'm trying to export a list of contacts with a specified set of fields from in Codeigniter. PHP is exiting early and I can't figure out why. It exports 4,092 contacts then exits but the count of the array being exported is 140,699. PHP gives me no errors, and on my test server the export function works fine. Here's the code:
function admin_export()
{
set_time_limit(0);
if(!$this->ion_auth->in_group(array('admin')) && !$this->input->is_cli_request())
die();
$contacts = $this->contacts_model->get_contacts();
$export_fields = unserialize($this->contacts_model->get_contact_export_fields());
if(!file_exists($this->config->item('tmp_path')))
mkdir($this->config->item('tmp_path'));
if($export_fields == false)
{
echo json_encode(false);
}
else
{
$fh = fopen($this->config->item('tmp_path').'export.csv', 'w');
fputcsv($fh, $export_fields, ',');
foreach($contacts as $i => $contact)
{
$id = $contact['id'];
foreach($contact as $k => $v)
{
if(!in_array($k, $export_fields))
{
unset($contacts[$i][$k]);
}
}
if(in_array('role', $export_fields))
{
$contacts[$i]['role'] = '';
$roles = $this->contacts_model->get_contact_roles($id);
foreach($roles as $role)
{
$contacts[$i]['role'] .= $role['role'].';';
}
$contacts[$i]['role'] = rtrim($contacts[$i]['role'], ';');
}
if(in_array('role_id', $export_fields))
{
$contacts[$i]['role_id'] = '';
$role_ids = $this->contacts_model->get_contact_roles($id);
foreach($role_ids as $role_id)
{
$contacts[$i]['role_id'] .= $role_id['id'].';';
}
$contacts[$i]['role_id'] = rtrim($contacts[$i]['role_id'], ';');
}
fputcsv($fh, $contacts[$i], ',');
}
fclose($fh);
echo json_encode(true);
}
}
What about memory? It's possible that it is maxing out the allocated memory and stopping.
I am doing a simple app that reads json data from 15 different URLs. I have a special need that I need to do this serverly. I am using file_get_contents($url).
Since I am using file_get_contents($url). I wrote a simple script, is it:
$websites = array(
$url1,
$url2,
$url3,
...
$url15
);
foreach ($websites as $website) {
$data[] = file_get_contents($website);
}
and it was proven to be very slow, because it waits for the first request and then do the next one.
If you mean multi-curl then, something like this might help:
$nodes = array($url1, $url2, $url3);
$node_count = count($nodes);
$curl_arr = array();
$master = curl_multi_init();
for($i = 0; $i < $node_count; $i++)
{
$url =$nodes[$i];
$curl_arr[$i] = curl_init($url);
curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($master, $curl_arr[$i]);
}
do {
curl_multi_exec($master,$running);
} while($running > 0);
for($i = 0; $i < $node_count; $i++)
{
$results[] = curl_multi_getcontent ( $curl_arr[$i] );
}
print_r($results);
i don't particularly like the approach of any of the existing answers
Timo's code: might sleep/select() during CURLM_CALL_MULTI_PERFORM which is wrong, it might also fail to sleep when ($still_running > 0 && $exec != CURLM_CALL_MULTI_PERFORM) which may make the code spin at 100% cpu usage (of 1 core) for no reason
Sudhir's code: will not sleep when $still_running > 0 , and spam-call the async-function curl_multi_exec() until everything has been downloaded, which cause php to use 100% cpu (of 1 cpu core) until everything has been downloaded, in other words it fails to sleep while downloading
here's an approach with neither of those issues:
$websites = array(
"http://google.com",
"http://example.org"
// $url2,
// $url3,
// ...
// $url15
);
$mh = curl_multi_init();
foreach ($websites as $website) {
$worker = curl_init($website);
curl_setopt_array($worker, [
CURLOPT_RETURNTRANSFER => 1
]);
curl_multi_add_handle($mh, $worker);
}
for (;;) {
$still_running = null;
do {
$err = curl_multi_exec($mh, $still_running);
} while ($err === CURLM_CALL_MULTI_PERFORM);
if ($err !== CURLM_OK) {
// handle curl multi error?
}
if ($still_running < 1) {
// all downloads completed
break;
}
// some haven't finished downloading, sleep until more data arrives:
curl_multi_select($mh, 1);
}
$results = [];
while (false !== ($info = curl_multi_info_read($mh))) {
if ($info["result"] !== CURLE_OK) {
// handle download error?
}
$results[curl_getinfo($info["handle"], CURLINFO_EFFECTIVE_URL)] = curl_multi_getcontent($info["handle"]);
curl_multi_remove_handle($mh, $info["handle"]);
curl_close($info["handle"]);
}
curl_multi_close($mh);
var_export($results);
note that an issue shared by all 3 approaches here (my answer, and Sudhir's answer, and Timo's answer) is that they will open all connections simultaneously, if you have 1,000,000 websites to fetch, these scripts will try to open 1,000,000 connections simultaneously. if you need to like.. only download 50 websites at a time, or something like that, maybe try:
$websites = array(
"http://google.com",
"http://example.org"
// $url2,
// $url3,
// ...
// $url15
);
var_dump(fetch_urls($websites,50));
function fetch_urls(array $urls, int $max_connections, int $timeout_ms = 10000, bool $return_fault_reason = true): array
{
if ($max_connections < 1) {
throw new InvalidArgumentException("max_connections MUST be >=1");
}
foreach ($urls as $key => $foo) {
if (! is_string($foo)) {
throw new \InvalidArgumentException("all urls must be strings!");
}
if (empty($foo)) {
unset($urls[$key]); // ?
}
}
unset($foo);
// DISABLED for benchmarking purposes: $urls = array_unique($urls); // remove duplicates.
$ret = array();
$mh = curl_multi_init();
$workers = array();
$work = function () use (&$ret, &$workers, &$mh, $return_fault_reason) {
// > If an added handle fails very quickly, it may never be counted as a running_handle
while (1) {
do {
$err = curl_multi_exec($mh, $still_running);
} while ($err === CURLM_CALL_MULTI_PERFORM);
if ($still_running < count($workers)) {
// some workers finished, fetch their response and close them
break;
}
$cms = curl_multi_select($mh, 1);
// var_dump('sr: ' . $still_running . " c: " . count($workers)." cms: ".$cms);
}
while (false !== ($info = curl_multi_info_read($mh))) {
// echo "NOT FALSE!";
// var_dump($info);
{
if ($info['msg'] !== CURLMSG_DONE) {
continue;
}
if ($info['result'] !== CURLE_OK) {
if ($return_fault_reason) {
$ret[$workers[(int) $info['handle']]] = print_r(array(
false,
$info['result'],
"curl_exec error " . $info['result'] . ": " . curl_strerror($info['result'])
), true);
}
} elseif (CURLE_OK !== ($err = curl_errno($info['handle']))) {
if ($return_fault_reason) {
$ret[$workers[(int) $info['handle']]] = print_r(array(
false,
$err,
"curl error " . $err . ": " . curl_strerror($err)
), true);
}
} else {
$ret[$workers[(int) $info['handle']]] = curl_multi_getcontent($info['handle']);
}
curl_multi_remove_handle($mh, $info['handle']);
assert(isset($workers[(int) $info['handle']]));
unset($workers[(int) $info['handle']]);
curl_close($info['handle']);
}
}
// echo "NO MORE INFO!";
};
foreach ($urls as $url) {
while (count($workers) >= $max_connections) {
// echo "TOO MANY WORKERS!\n";
$work();
}
$neww = curl_init($url);
if (! $neww) {
trigger_error("curl_init() failed! probably means that max_connections is too high and you ran out of system resources", E_USER_WARNING);
if ($return_fault_reason) {
$ret[$url] = array(
false,
- 1,
"curl_init() failed"
);
}
continue;
}
$workers[(int) $neww] = $url;
curl_setopt_array($neww, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_TIMEOUT_MS => $timeout_ms
));
curl_multi_add_handle($mh, $neww);
// curl_multi_exec($mh, $unused_here); LIKELY TO BE MUCH SLOWER IF DONE IN THIS LOOP: TOO MANY SYSCALLS
}
while (count($workers) > 0) {
// echo "WAITING FOR WORKERS TO BECOME 0!";
// var_dump(count($workers));
$work();
}
curl_multi_close($mh);
return $ret;
}
that will download the entire list and not download more than 50 urls simultaneously
(but even that approach stores all the results in-ram, so even that approach may end up running out of ram; if you want to store it in a database instead of in ram, the curl_multi_getcontent part can be modified to store it in a database instead of in a ram-persistent variable.)
I would like to provide a more complete example without hitting the CPU at 100% and crashing when there's a slight error or something unexpected.
It also shows you how to fetch the headers, the body, request info and manual redirect following.
Disclaimer, this code is intended to be extended and implemented into a library or as a quick starting point, and as such the functions inside of it are kept to a minimum.
function mtime(){
return microtime(true);
}
function ptime($prev){
$t = microtime(true) - $prev;
$t = $t * 1000;
return str_pad($t, 20, 0, STR_PAD_RIGHT);
}
// This function exists to add compatibility for CURLM_CALL_MULTI_PERFORM for old curl versions, on modern curl it will only run once and be the equivalent of calling curl_multi_exec
function curl_multi_exec_full($mh, &$still_running) {
// In theory curl_multi_exec should never return CURLM_CALL_MULTI_PERFORM (-1) because it has been deprecated
// In practice it sometimes does
// So imagine that this just runs curl_multi_exec once and returns it's value
do {
$state = curl_multi_exec($mh, $still_running);
// curl_multi_select($mh, $timeout) simply blocks for $timeout seconds while curl_multi_exec() returns CURLM_CALL_MULTI_PERFORM
// We add it to prevent CPU 100% usage in case this thing misbehaves (especially for old curl on windows)
} while ($still_running > 0 && $state === CURLM_CALL_MULTI_PERFORM && curl_multi_select($mh, 0.1));
return $state;
}
// This function replaces curl_multi_select and makes the name make more sense, since all we're doing is waiting for curl, it also forces a minimum sleep time between requests to avoid excessive CPU usage.
function curl_multi_wait($mh, $minTime = 0.001, $maxTime = 1){
$umin = $minTime*1000000;
$start_time = microtime(true);
// it sleeps until there is some activity on any of the descriptors (curl files)
// it returns the number of descriptors (curl files that can have activity)
$num_descriptors = curl_multi_select($mh, $maxTime);
// if the system returns -1, it means that the wait time is unknown, and we have to decide the minimum time to wait
// but our `$timespan` check below catches this edge case, so this `if` isn't really necessary
if($num_descriptors === -1){
usleep($umin);
}
$timespan = (microtime(true) - $start_time);
// This thing runs very fast, up to 1000 times for 2 urls, which wastes a lot of CPU
// This will reduce the runs so that each interval is separated by at least minTime
if($timespan < $umin){
usleep($umin - $timespan);
//print "sleep for ".($umin - $timeDiff).PHP_EOL;
}
}
$handles = [
[
CURLOPT_URL=>"http://example.com/",
CURLOPT_HEADER=>false,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_FOLLOWLOCATION=>false,
],
[
CURLOPT_URL=>"http://www.php.net",
CURLOPT_HEADER=>false,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_FOLLOWLOCATION=>false,
// this function is called by curl for each header received
// This complies with RFC822 and RFC2616, please do not suggest edits to make use of the mb_ string functions, it is incorrect!
// https://stackoverflow.com/a/41135574
CURLOPT_HEADERFUNCTION=>function($ch, $header)
{
print "header from http://www.php.net: ".$header;
//$header = explode(':', $header, 2);
//if (count($header) < 2){ // ignore invalid headers
// return $len;
//}
//$headers[strtolower(trim($header[0]))][] = trim($header[1]);
return strlen($header);
}
]
];
//create the multiple cURL handle
$mh = curl_multi_init();
$chandles = [];
foreach($handles as $opts) {
// create cURL resources
$ch = curl_init();
// set URL and other appropriate options
curl_setopt_array($ch, $opts);
// add the handle
curl_multi_add_handle($mh, $ch);
$chandles[] = $ch;
}
//execute the multi handle
$prevRunning = null;
$count = 0;
do {
$time = mtime();
// $running contains the number of currently running requests
$status = curl_multi_exec_full($mh, $running);
$count++;
print ptime($time).": curl_multi_exec status=$status running $running".PHP_EOL;
// One less is running, meaning one has finished
if($running < $prevRunning){
print ptime($time).": curl_multi_info_read".PHP_EOL;
// msg: The CURLMSG_DONE constant. Other return values are currently not available.
// result: One of the CURLE_* constants. If everything is OK, the CURLE_OK will be the result.
// handle: Resource of type curl indicates the handle which it concerns.
while ($read = curl_multi_info_read($mh, $msgs_in_queue)) {
$info = curl_getinfo($read['handle']);
if($read['result'] !== CURLE_OK){
// handle the error somehow
print "Error: ".$info['url'].PHP_EOL;
}
if($read['result'] === CURLE_OK){
/*
// This will automatically follow the redirect and still give you control over the previous page
// TODO: max redirect checks and redirect timeouts
if(isset($info['redirect_url']) && trim($info['redirect_url'])!==''){
print "running redirect: ".$info['redirect_url'].PHP_EOL;
$ch3 = curl_init();
curl_setopt($ch3, CURLOPT_URL, $info['redirect_url']);
curl_setopt($ch3, CURLOPT_HEADER, 0);
curl_setopt($ch3, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch3, CURLOPT_FOLLOWLOCATION, 0);
curl_multi_add_handle($mh,$ch3);
}
*/
print_r($info);
$body = curl_multi_getcontent($read['handle']);
print $body;
}
}
}
// Still running? keep waiting...
if ($running > 0) {
curl_multi_wait($mh);
}
$prevRunning = $running;
} while ($running > 0 && $status == CURLM_OK);
//close the handles
foreach($chandles as $ch){
curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);
print $count.PHP_EOL;
I have checked the memory whilst sending and receiving data over one connection, and I appear to be correctly clearing variables, as the memory returns to its previous value.
But for some reason if I make a new connection, then close the connection, memory is leaked. I believe the problem may be occurring when a socket is accepted.
I am using PHP 5.2.10
Hopefully one of you can find the time to have a play with the source and figure out where its gone wrong. Thanks in advance
<?php
Class SuperSocket
{
var $listen = array();
var $status_listening = FALSE;
var $sockets = array();
var $event_callbacks = array();
var $recvq = 1;
var $parent;
var $delay = 100; // 10,000th of a second
var $data_buffer = array();
function SuperSocket($listen = array('127.0.0.1:123'))
{
$listen = array_unique($listen);
foreach ($listen as $address)
{
list($address, $port) = explode(":", $address, 2);
$this->listen[] = array("ADDR" => trim($address), "PORT" => trim($port));
};
}
function start()
{
if ($this->status_listening)
{
return FALSE;
};
$this->sockets = array();
$cursocket = 0;
foreach ($this->listen as $listen)
{
if ($listen['ADDR'] == "*")
{
$this->sockets[$cursocket]['socket'] = socket_create_listen($listen['PORT']);
$listen['ADDR'] = FALSE;
}
else
{
$this->sockets[$cursocket]['socket'] = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
};
if ($this->sockets[$cursocket]['socket'] < 0)
{
return FALSE;
};
if (#socket_bind($this->sockets[$cursocket]['socket'], $listen['ADDR'], $listen['PORT']) < 0)
{
return FALSE;
};
if (socket_listen($this->sockets[$cursocket]['socket']) < 0)
{
return FALSE;
};
if (!socket_set_option($this->sockets[$cursocket]['socket'], SOL_SOCKET, SO_REUSEADDR, 1))
{
return FALSE;
};
if (!socket_set_nonblock($this->sockets[$cursocket]['socket']))
{
return FALSE;
};
$this->sockets[$cursocket]['info'] = array("ADDR" => $listen['ADDR'], "PORT" => $listen['PORT']);
$this->sockets[$cursocket]['channels'] = array();
$this->sockets[$cursocket]['id'] = $cursocket;
$cursocket++;
};
$this->status_listening = TRUE;
}
function new_socket_loop(&$socket)
{
$socket =& $this->sockets[$socket['id']];
if ($newchannel = #stream_socket_accept($socket['socket'], 0));//#socket_accept($socket['socket']))
{
socket_set_nonblock($newchannel);
$socket['channels'][]['socket'] = $newchannel;
$channel = array_pop(array_keys($socket['channels']));
$this->remote_address($newchannel, $remote_addr, $remote_port);
$socket['channels'][$channel]['info'] = array('ADDR' => $remote_addr, 'PORT' => $remote_port);
$event = $this->event("NEW_SOCKET_CHANNEL");
if ($event)
$event($socket['id'], $channel, $this);
};
}
function endswith($string, $test) {
$strlen = strlen($string);
$testlen = strlen($test);
if ($testlen > $strlen) return false;
return substr_compare($string, $test, -$testlen) === 0;
}
function recv_socket_loop(&$socket)
{
$socket =& $this->sockets[$socket['id']];
foreach ($socket['channels'] as $channel_id => $channel)
{
unset($buffer);#Flush buffer
$status = #socket_recv($channel['socket'], $buffer, $this->recvq, 0);
if ($status === 0 && $buffer === NULL)
{
$this->close($socket['id'], $channel_id);
}
elseif (!($status === FALSE && $buffer === NULL))
{
$sockid = $socket['id'];
if(!isset($this->data_buffer[$sockid]))
$this->data_buffer[$sockid]='';
if($buffer!="\r"&&$buffer!="\n")
{
//Putty ends with \r\n
$this->data_buffer[$sockid].=$buffer;
}
else if($buffer!="\n") //ignore the additional newline char \n
{
$event = $this->event("DATA_SOCKET_CHANNEL");
if ($event)
$event($socket['id'], $channel_id, $this->data_buffer[$sockid], $this);
unset($this->data_buffer[$sockid]);
}
};
}
}
function stop()
{
$this->closeall();
$this->status_listening = FALSE;
foreach ($this->sockets as $socket_id => $socket)
{
socket_shutdown($socket['socket']);
socket_close($socket['socket']);
};
$event = $this->event("SERVER_STOP");
if ($event)
$event($this);
}
function closeall($socket_id = NULL)
{
if ($socket_id === NULL)
{
foreach ($this->sockets as $socket_id => $socket)
{
foreach ($socket['channels'] as $channel_id => $channel)
{
$this->close($socket_id, $channel_id);
}
}
}
else
{
foreach ($this->sockets[$socket_id]['channels'] as $channel_id => $channel)
{
$this->close($socket_id, $channel_id);
};
};
}
function close($socket_id, $channel_id)
{
unset($this->data_buffer[$socket_id]); //clear the sockets data buffer
$arrOpt = array('l_onoff' => 1, 'l_linger' => 1);
#socket_shutdown($this->sockets[$socket_id]['channels'][$channel_id]['socket']);
#socket_close($this->sockets[$socket_id]['channels'][$channel_id]['socket']);
$event = $this->event("LOST_SOCKET_CHANNEL");
if ($event)
$event($socket_id, $channel_id, $this);
}
function loop()
{
while ($this->status_listening)
{
usleep($this->delay);
foreach ($this->sockets as $socket)
{
$this->new_socket_loop($socket);
$this->recv_socket_loop($socket);
};
$event = $this->event("END_SOCKET_CHANNEL");
if ($event)
$event($this);
};
}
function write($socket_id, $channel_id, $buffer)
{
#socket_write($this->sockets[$socket_id]['channels'][$channel_id]['socket'], $buffer);
#socket_write($this->sockets[$socket_id]['channels'][$channel_id]['socket'], 'Server memory usage: '.memory_get_usage().'/'.memory_get_peak_usage(true)."\r\n");
}
function get_channel_info($socket_id, $channel_id)
{
return $this->sockets[$socket_id]['channels'][$channel_id]['info'];
}
function get_socket_info($socket_id)
{
$socket_info = $this->sockets[$socket_id]['info'];
if (empty($socket_info['ADDR']))
{
$socket_info['ADDR'] = "*";
};
return $socket_info;
}
function get_raw_channel_socket($socket_id, $channel_id)
{
return $this->sockets[$socket_id]['channels'][$channel_id]['socket'];
}
function remote_address($channel_socket, &$ipaddress, &$port)
{
socket_getpeername($channel_socket, $ipaddress, $port);
}
function event($name)
{
if (isset($this->event_callbacks[$name]))
return $this->event_callbacks[$name];
}
function assign_callback($name, $function_name)
{
$this->event_callbacks[$name] = $function_name;
}
};
?>
Server.php
include("supersocket.class.php");
function startswith($string, $test) {
return strpos($string, $test, 0) === 0;
}
function newdata($socket_id, $channel_id, $buffer, &$server)
{
//$server->write($socket_id, $channel_id, ">".$buffer."\r\n");
if($buffer=="STOP")
{
$server->stop();
}
else if($buffer=="DATETIME")
{
$server->write($socket_id, $channel_id, ">".date("dmYHis")."\r\n");
}
else
{
$server->write($socket_id, $channel_id, ">BAD\r\n");
}
};
function newclient($socket_id, $channel_id, &$server)
{
$server->write($socket_id, $channel_id, "HEADER\n\r");
}
$socket = new SuperSocket(array('127.0.0.1:12345'));
$socket->assign_callback("DATA_SOCKET_CHANNEL", "newdata");
$socket->assign_callback("NEW_SOCKET_CHANNEL", "newclient");
$socket->start();
//set_time_limit(60*2);
set_time_limit(60*60*24*5); //5 days
$socket->loop();
Edit: sorry you might need to change the socket accept back to:
if ($newchannel = #socket_accept($socket['socket']))
then close the connection, memory is leaked
This is a tricky one - even the standard reference counting garbage collector only kicks in at intervals which are difficult to predict. Calling gc_collect_cycles() should trigger the gc though. Try calling that whenever you close a connection and see if it makes a difference.
If you're still seeing problems - then check if you've got the cyclic reference counter compiled in - if not, then get it.
The Channel array was never removed upon closing the connection, surprised no one picked up on this. Memory usage is now super tight.
unset($this->sockets[$socket_id]['channels'][$channel_id]);
But it does mean that any event for LOST_SOCKET_CHANNEL is pretty useless for the time being.
Will accept my own answer when stack over flow allows. Thanks for all your help ppl .. i guess..