3

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?

2 Answers 2

4

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' ) );
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Quamis; I respectfully disagree. Although it "doesn't do telnet", it will open a socket to write out a GET request, but instead of doing it manually, PHP will manage the socket. That's an easier approach.
... from the question i thought he really needed to do a telnet session, not a simple http get(which i thought he already mastered).. i can't retract my -1 it seems :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.