Question

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?

Was it helpful?

Solution

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

OTHER TIPS

You really want to do this with telnet? What about:

echo file_get_contents("http://127.0.0.1:80");

Or if You want to customize the request, you can use cURL - http://php.net/manual/en/book.curl.php

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