I want to read a line (ending with \x0D\x0A
) from a PHP socket, and strip the telnet control charaters (IAC, WILL, DO, etc) from it. Currently I'm using this:
<?php
// snip
function socket_readline($socket, $echo = true) {
$buffer = "";
$bufsize = 0;
$length = 4096;
$need = $length;
while ($bufsize < $length) {
$read = array($socket);
$write = null;
$except = null;
$changes = socket_select($read, $write, $except, null);
if ($changes > 0) {
$in = socket_read($read[0], 1);
while ($in == TELNET_IAC) {
$in = socket_read($read[0], 1);
if ($in == TELNET_WILL or $in == TELNET_WONT
or $in == TELNET_DO or $in == TELNET_DONT) {
socket_read($read[0], 1);
$in = socket_read($read[0], 1);
}
elseif ($in == TELNET_SB) {
do { $in = socket_read($read[0], 1); } while ($in != TELNET_SE);
}
}
if ($echo or $in == "\x0A" or $in == "\x0D") socket_write($read[0], $in);
$insize = strlen($in);
$buffer .= $in; $bufsize += $insize;
if ($in == "" or $in == "\x0A") break;
}
}
return rtrim($buffer, "\x0D\x0A");
}
?>
...but it just feels too hackish. Is there a better way?