【问题标题】:How to get output, when using fsockopen to open a php page?使用 fsockopen 打开 php 页面时如何获取输出?
【发布时间】:2014-10-03 04:38:09
【问题描述】:

当我使用 fsockopen 打开一个 php 页面时,代码工作正常,但还有一些其他问题。例如:如果我在 a.php 中打开 b.php,“echo”将无法在 b.php 中工作,错误消息也不会(这 2 件事在公共页面上工作正常)。这使得调试非常困难。如何在页面b中获得输出?

非常感谢!这是我的代码。我使用 main.php 来调用 main_single_block.php.PS:除了我上面提到的 2 件事之外,所有事情都正常工作。

main.php:

$template_url_arr_s = serialize($template_url_arr);
$fp = fsockopen($sochost, intval($socportno), $errno, $errstr, intval($soctimeout));
if (!$fp) {
    echo "$errstr ($errno) ,open sock erro.<br/>\n";
}
$typename=  urlencode($typename);//do url encode (if not, ' 'can not be handled right)
$template_url_arr_s=  urlencode($template_url_arr_s);
*$out = "GET /main/main_single_block.php?typename=" . $typename . "&templateurlarr=" . $template_url_arr_s . "\r\n";*
fputs($fp, $out);
fclose($fp);

【问题讨论】:

  • 你打开HTTP端口了吗? PHP 脚本仅在您通过网络服务器访问它们时才会执行,而不是作为普通文件。
  • 您似乎没有从套接字读取输出。因此,如果脚本回显了某些内容,那么您就没有对它做任何事情。
  • 你为什么不用file_get_contents
  • 是的,我打开了一个 http 端口。我使用此代码执行多线程工作,这意味着在 main.php 调用它之后,一对“main_single_block.php”“同时”工作。我似乎多线程的东西工作正常,但我怎样才能从每个“main_single_block.php”获取输出消息(例如echo'123')用于调试目的。
  • PS:我从网上学到了多线程的东西...

标签: php output fsockopen


【解决方案1】:

这是基本结构:

template_url_arr_s = serialize($template_url_arr);
$fp = fsockopen($sochost, intval($socportno), $errno, $errstr, intval($soctimeout));
if (!$fp) {
    echo "$errstr ($errno) ,open sock erro.<br/>\n";
}
$typename=  urlencode($typename);//do url encode (if not, ' 'can not be handled right)
$template_url_arr_s=  urlencode($template_url_arr_s);
$out = "GET /main/main_single_block.php?typename=" . $typename . "&templateurlarr=" . $template_url_arr_s . " HTTP/1.1\r\nHost: $sochost\r\nConnection: close\r\n\r\n";
fputs($fp, $out);
// First read until the end of the response header, look for blank line
while ($line = fgets($fp)) {
    $line = trim($line);
    if ($line == "") {
        break;
    }
}
$output = '';
// Read the body of the response
while ($line = fgets($fp)) {
    $output .= $line;
}
fclose($fp);

我已将HTTP/1.1 参数添加到GET 行的末尾、所需的Host: 标头和Connection: close 标头,因此我不需要处理解析Content-Length: 标头的响应。

一个真正的应用程序应该解析响应头,我上面的代码只是跳过它们。标头以空行结束,然后将其余的输出收集到一个变量中。

【讨论】:

  • 嗨,你能帮我解决我在问题“使用 php 时 http 响应中的 Stange 字符串”的新问题吗?非常感谢!
猜你喜欢
  • 2014-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
  • 2014-04-25
  • 2012-11-04
相关资源
最近更新 更多