3

我需要远程登录到一个端口并发送命令并使用 PHP 将输出写入 txt 文件。我是怎么做的?

在这个论坛有一个相同的问题名称使用 PHP 的 telnet 连接,但他们有一个解决方案链接,并且解决方案链接没有打开,所以我必须再次提出问题。

我也从php 站点尝试下面的代码,但它没有将正确的输出保存到文本文件中。代码:

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

所以,请帮我解决这个问题。我如何远程登录到 localhost 端口 80 并发送命令 GET / HTTP/1.1 并将输出写入文本文件?

4

2 回答 2

4

通过简单的添加,您的示例脚本可以将输出写入文件,当然:

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

再说一次,我同意 Eduard7;不手动执行请求更容易,让 PHP 为您解决它:

<?php
// This is much easier, I imagine?
file_put_contents( 'output.txt', file_get_contents( 'http://localhost' ) );
于 2011-05-23T09:08:37.253 回答
0

你真的想用 telnet 做这个吗?关于什么:

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

或者,如果您想自定义请求,可以使用 cURL - http://php.net/manual/en/book.curl.php

于 2011-05-23T09:03:34.013 回答