How to get output, when using fsockopen to open a php page?

随声附和 提交于 2020-01-05 10:10:53

问题


when I use fsockopen to open a php page, the code works fine, but there are some other problems. For Example: if I open b.php in a.php, "echo" won't work in b.php, error message neither(these 2 things works fine on common page). This makes debug very difficult. How to get output in page b?

Thanks a lot! here is my code. I use main.php to call main_single_block.php.PS: all things work fine except the 2 things I mentiond above.

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

回答1:


Here's the basic structure:

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

I've added the HTTP/1.1 parameter to the end of the GET line, the required Host: header, and a Connection: close header so I don't need to deal with parsing the Content-Length: header of the response.

A real application should parse the response headers, my code above just skips over them. The header is terminated by a blank line, then it collects the rest of the output into a variable.



来源:https://stackoverflow.com/questions/26173349/how-to-get-output-when-using-fsockopen-to-open-a-php-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!