CURL语句合二为一

时间:2015-03-13 19:19:04

标签: php curl controller

我的app控制器文件中有一堆curl语句。我怎么可能将它们全部合并到一个curl语句中。它甚至可能吗?感谢

    // used for curl and curl_post
    curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

    // used for curl_twitter
    curl_setopt($ch, CURLOPT_USERAGENT,'spider');

    // used for curl_post, curl_auth
    curl_setopt($ch,CURLOPT_POST, count($post_data_count));
    curl_setopt($ch,CURLOPT_POSTFIELDS, $post_data_string);

    // used for curl_twitter
    curl_setopt($ch, CURLOPT_HEADER, true);



    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);C

1 个答案:

答案 0 :(得分:1)

如果每次创建函数时使用相同的curl语句,只需通过参数传递所需的更改。

function curlPerform($url, $postfields, $useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'){
    $ch = curl_init($url);
    // used for curl and curl_post
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    // used for curl_post, curl_auth
    curl_setopt($ch,CURLOPT_POST, count($postfields));
    curl_setopt($ch,CURLOPT_POSTFIELDS, $postfields);
    // used for curl_twitter
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    $reponse = curl_exec($ch);
    curl_close($ch);
    return $reponse;
}

$reponse = curlPerform($yourUrl, $yourPostFields); // Each time that you want to run a curl request just call this function DRY

或使用curl_setopt_array

$ch = curl_init();

$options = array(CURLOPT_URL => 'http://www.example.com/',
                 CURLOPT_HEADER => false
                );

curl_setopt_array($ch, $options);

curl_exec($ch);

curl_close($ch);