Reputation: 317
ive ran into an issue while creating a PHP telnet script at work to gather network data.
as the amount of data returned from the 'Action: Status' command could be of any size... im concerned about using a static number with fread() on line 13. I have also tried using fgets() instead but it only grabs the first line of data (the META HTTP line... without the table). how can I grab an arbitrary amount of data from the socket using PHP? please help
<?php
$ami = fsockopen("192.100.100.180", 5038, $errno, $errstr);
if (!$ami) {
echo "ERROR: $errno - $errstr<br />\n";
} else {
fwrite($ami, "Action: Login\r\nUsername: 1005\r\nSecret: password\r\nEvents: off\r\n\r\n");
fwrite($ami, "Action: Status\r\n\r\n");
sleep(1);
$record = fread($ami,9999);#this line could over run!!!
$record = explode("\r\n", $record);
echo "<META HTTP-EQUIV=Refresh CONTENT=\"9\">"; #refresh page every 9 seconds
echo "<table border=\"1\">";
foreach($record as $value){
if(!strlen(stristr($value,'Asterisk'))>0
&& !strlen(stristr($value,'Response'))>0
&& !strlen(stristr($value,'Message'))>0
&& !strlen(stristr($value,'Event'))>0
&& strlen(strpos($value,' '))>0) #remove blank lines
php_table($value);;
}
echo "</table>";
fclose($ami);
}
function php_table($value){
$row1 = true;
$value = explode(" ", $value);
foreach($value as $field){
if($row1){
echo "<tr><td>".$field."</td>";
$row1 = false;
}
else{
echo "<td>".$field."</td></tr>";
$row1 = true;
}
}
}
?>
Upvotes: 3
Views: 8343
Reputation: 18071
while (strlen($c = fread($fp, 1024)) > 0) {
$record .= $c;
}
Edit: Your application hangs because it's not closing the connection to signify the end of a HTTP request. Try
fwrite($ami, "Action: Status\r\n\r\n");
fwrite($ami, "Connection: Close\r\n\r\n");
Upvotes: 4
Reputation: 19319
Just use a loop and look for the "end of the file"
$record = '';
while( !feof( $ami ) ) {
$record .= fread($ami,9999);
}
You should probably consider using smaller chunks.
Upvotes: 0
Reputation: 4311
$data = '';
while (!feof($ami)) {
$data .= fread($ami, 1024);
}
or in php5
$data = stream_get_contents($ami);
Upvotes: 5