curl 封装类 php,curl封装类

/**

* 2018-01-26

* justin

*/

class HttpCurl

{

private static $url     =   '';         // 访问的url

private static $oriUrl  =   '';         // referer url

private static $data    =   array();    // 可能发出的数据 post,put

private static $method  =   'get';      // 访问方式,默认是GET请求

private static $times   =   0;          // 请求超时设置

public static function send($url, $data = array(), $method = 'get' , $time = 0 )

{

if (!$url) exit('url can not be null');

self::$times   =    $time;

self::$url     =    $url;

self::$method  =    $method;

$urlArr        =    parse_url($url);

self::$oriUrl  =    $urlArr['scheme'] . '://' . $urlArr['host'];

self::$data    =    $data;

if (!in_array( self::$method, array('get', 'post', 'put', 'delete') ) )

{

exit('error request method type!');

}

$func  =    self::$method . 'Request';

return self::$func(self::$url);

}

/**

* 基础发起curl请求函数

* @param int $is_post 是否是post请求

*/

private static function doRequest($is_post = 0)

{

$ch = curl_init();//初始化curl

curl_setopt($ch, CURLOPT_URL, self::$url);//抓取指定网页

curl_setopt($ch, CURLOPT_AUTOREFERER, true); // 来源一定要设置成来自本站

curl_setopt($ch, CURLOPT_REFERER, self::$oriUrl);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上

if(true == self::$times){

curl_setopt($ch, CURLOPT_NOSIGNAL, 1);     //注意,毫秒超时一定要设置这个

curl_setopt($ch, CURLOPT_TIMEOUT_MS,self::$times); //超时毫秒,cURL 7.16.2中被加入。从PHP 5.2.3起可使用

}

if (true == $is_post) curl_setopt($ch, CURLOPT_POST, $is_post);//post提交方式

if (!empty(self::$data)) {

self::$data = self::dealPostData(self::$data);

curl_setopt($ch, CURLOPT_POSTFIELDS, self::$data);

}

$data = curl_exec($ch);//运行curl

curl_close($ch);

return $data;

}

/**

* 发起get请求

*/

public static function getRequest()

{

return self::doRequest(0);

}

/**

* 发起post请求

*/

public static function postRequest()

{

return self::doRequest(1);

}

/**

* 处理发起非get请求的传输数据

*

* @param array $postData

*/

public static function dealPostData($postData)

{

$o = '';

if (!is_array($postData)) exit('post data should be array');

foreach ($postData as $k => $v) {

$o .= "$k=" . urlencode($v) . "&";

}

$postData = mb_substr($o, 0, -1);

return mb_substr($o, 0, -1);

}

/**

* 发起put请求

*/

public static function putRequest($param)

{

return self::doRequest(2);

}

/**

* 发起delete请求

*/

public static function deleteRequest($param)

{

return self::doRequest(3);

}

}

调用方法:<?php

include('HttpCurl.class.php');

$res = HttpCurl::send('http://www.baidu.com/', array('ip' => '61.142.206.145'), 'post',1000);

var_dump($res);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值