PHP fsockopen函数说明:

Open Internet or Unix domain socket connection(打开套接字链接)

Initiates a socket connection to the resource specified by target .

fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets() , fgetss() , fwrite() , fclose() , and feof() ).就是返回一个文件句柄

开启PHP fsockopen这个函数

PHP fsockopen需要 PHP.ini 中 allow_url_fopen 选项开启

例子如下:

 
 
  1. $fp = fsockopen("www.example.com",
    80, $errno, $errstr, 30);

  2. if (!$fp) {

  3. echo "$errstr ($errno)<br/>\n";

  4. } else {

  5. $out = "GET / HTTP/1.1\r\n";

  6. $out .= "Host: www.example.com\r\n";

  7. $out .= "Connection: Close\r\n\r\n";

  8. fwrite($fp, $out);

  9. while (!feof($fp)) {

  10. echo fgets($fp, 128);

  11. }

  12. fclose($fp);

  13. }


处理下载问题时,所用到的方法

function downloadFile($file) {
$host = '********';

$out = "GET $file HTTP/1.0\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n\r\n";

$fp = fsockopen($host, 80);
fwrite($fp, $out);

$headers = array();
$body = '';
$filenameExt = '';
$isBody = false;
while(true) {
$line = fgets($fp);
if (false === $line) {
break;
}
if ($line == "\r\n") {
$isBody = true;
continue;
}

if ($isBody) {
$body .= $line;
echo strlen($body) . " ... \r";
} else {
if (strpos($line, 'filename')) {
preg_match('!filename="(.+?)\.([\w]+)"!', $line, $filename);
$filenameExt = $filename[2];
}
$headers[] = trim($line);
}
}
fclose($fp);

return array('fileExt' => $filenameExt, 'headers' => $headers, 'body' => $body);
}

你可能感兴趣的:(PHP,用法,fsockopen函数)