Question

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;
            }
        }
}

?>
Was it helpful?

Solution

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");

OTHER TIPS

$data = '';
while (!feof($ami)) {
  $data .= fread($ami, 1024);
}

or in php5

$data = stream_get_contents($ami);

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top