Home > 感悟 > 分析下这两个函数的区别:fsocket和curl实现相同的功能

function socket($host, $url, $content, $port = 80) {
$data = “POST ” . $url . ” HTTP/1.1\r\n”;
$data .= “Host: ” . $host . “\r\n”;
$data .= “Content-Type: application/x-www-form-urlencoded\r\n”;
$data .= “Content-Length: ” . strlen($content) . “\r\n”;
$data .= “\r\n”;
$data .= $content . “\r\n\r\n”;
$ock = fsockopen($host, $port);
if (!$ock) {
echo ‘No response from ‘ . $host . “\n”;;
}
fwrite($ock, $data);
$r = “”;
while (!feof($ock)) {
$r .= fgets($ock, 1024);
}
preg_match(“/(\{.+\})/”, $r, $m);
fclose($ock);
return $m[1];
}
function socket_by_curl($host, $url, $content, $port = 80) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Content-Type: application/x-www-form-urlencoded’));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$r = curl_exec($ch);
curl_close($ch);
preg_match(“/(\{.+\})/”, $r, $m);
return $m[1];
}

本站内容受著作权法保护。个人 blog 转载时请遵循 “署名-非商业用途-保持一致” 的创作共用协议;商业网站或未授权媒体不得复制本站内容。
Categories: 感悟 Tags:

Comments (0) Trackbacks (0) 本篇共有 0 篇评论↓
  1. No comments yet.
  1. No trackbacks yet.