How to connect telnet and send command and write output into text file using php

riad picture riad · May 23, 2011 · Viewed 12.4k times · Source

i need to telnet to a port and send command and write the output into a txt file using PHP.How i do it?

in this forum have a same question name telnet connection using PHP but their have a solution link and the solution link is not open so i have to make the question again.

Also i try the code below from php site but it does not save the proper output into a text file.Code:

<?php
$fp = fsockopen("localhost", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: localhost\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

So,please help me to solve the problem.How i telnet to localhost port 80 and send command GET / HTTP/1.1 and write the output into a text file?

Answer

Berry Langerak picture Berry Langerak · May 23, 2011

With a simple additition, your example script can write the output to a file, of course:

<?php
$fp = fsockopen("localhost", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: localhost\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);

    $output = '';
    while (!feof($fp)) {
        $output .= fgets($fp, 128);
    }

    fclose($fp);
    file_put_contents( 'output.txt', $output );
}

Then again, I agree with Eduard7; it's easier not to do the request manually and just let PHP solve it for you:

<?php
// This is much easier, I imagine?
file_put_contents( 'output.txt', file_get_contents( 'http://localhost' ) );