php curl , fsockopen 函数

下面直接给出 使用 curl 和 fsockopen 的例子,你可以当成使用实例,也可以直接当作封装好的函数直接使用。

curl函数使用代码

public function xcurl($url,$ref=null,$post=array(),$ua="Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre",$print=false) {
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_AUTOREFERER, true);
     if(!empty($ref)) {
          curl_setopt($ch, CURLOPT_REFERER, $ref);
     }
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     if(!empty($ua)) {
          curl_setopt($ch, CURLOPT_USERAGENT, $ua);
     }
     if(count($post) > 0){
          curl_setopt($ch, CURLOPT_POST, 1);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
     }
     $output = curl_exec($ch);
     curl_close($ch);
     if($print) {
          print($output);
     } else {
          return $output;
     }
}

fsockopen 函数使用代码:

public function curl_request_async($url, $params, $type='GET')
    {
    // set referer
        $referer = $_SERVER['HTTP_HOST'];
        foreach ($params as $key => &$val) {
            if (is_array($val)) $val = implode(',', $val);
            $post_params[] = $key.'='.urlencode($val);
        }
        $post_string = implode('&', $post_params);

        $parts=parse_url($url);

        @$fp = fsockopen($parts['host'], isset($parts['port'])?$parts['port']:80, $errno, $errstr, 2);

        if(!$fp){
            echo "$errstr ($errno)<br />n";
        }else{
            if('GET' == $type) $parts['path'] .= '?'.$post_string;

            $out = "$type ".$parts['path']." HTTP/1.1rn";
            $out.= "Host: ".$parts['host']."rn";
            $out.= "Referer: ".$referer."rn";
            $out.= "Content-Type: application/x-www-form-urlencodedrn";
            $out.= "Connection: Closernrn";
            // Data goes in the request body for a POST request
            if ('POST' == $type && isset($post_string)) $out.= $post_string;
            fwrite($fp, $out);

            fclose($fp);
        }
    }

仅仅 从如上的函数,使用上的区别其中重要的一点就是:
curl 请求某个Url 需要等待结果返回,而 fsockopen 不需要返回,发送请求后就继续执行代码。除非你使用 fsockopen 需要打印请求后返回的结果。

$(function () {
$('pre.prettyprint code').each(function () {
var lines = $(this).text().split('n').length;
var $numbering = $('

    ').addClass('pre-numbering').hide();
    $(this).addClass('has-numbering').parent().append($numbering);
    for (i = 1; i <= lines; i++) {
    $numbering.append($('
  • ').text(i));
    };
    $numbering.fadeIn(1700);
    });
    });

此文章通过 python 爬虫创建,原文是自己的csdn 地址: php curl , fsockopen 函数



欢迎转载,转载请注明来源:php curl , fsockopen 函数

发表评论

电子邮件地址不会被公开。