php简单的实现curl类

闲话少说,我就直接上代码了,这里只是简单的实现curl类,其中有很多地方都还不完善。

<?php 
/**
 * curl类,实现get和post方法
 */
class HttpClient{
	/**
	 * *
	 * @param  string  $url     请求的url
	 * @param  integer $timeout 允许curl执行的时间
	 * @param  boolean $type    返回时是否json_decode
	 * @return            		返回内容
	 */
	public static function get($url, $timeout = 1000, $type = true){
		$curl = curl_init();
		curl_setopt($curl,CURLOPT_URL,$url);
		curl_setopt($curl,CURLOPT_HTTPGET,1);//设置为get请求
		curl_setopt($curl,CURLOPT_HEADER,0);//不输出返回头信息
		curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);//以文件流的形式返回,而不是直接输出
		curl_setopt($curl,CURLOPT_CONNECTTIMEOUT_MS, 3000);//允许的链接时间  毫秒
		curl_setopt($curl,CURLOPT_TIMEOUT_MS,$timeout);//允许的执行时间
		curl_setopt($curl,CURLOPT_HTTPHEADER,array('X-FORWARDED-FOR:' .$_SERVER['REMOTE_ADDR']));
		$res = curl_exec($curl);
		curl_close($curl);
		return $type?json_decode($res,true):$res;
	}
	/**
	 * *
	 * @param  string  $url     请求的url
	 * @param  array   $data    post请求的数据
	 * @param  integer $timeout 允许执行的时间
	 * @param  boolean $type    返回时是否json_decode
	 * @return            		返回内容
	 */
	public static function post($url, $data, $timeout = 1000, $type = true){
		$curl = curl_init();
		curl_setopt($curl,CURLOPT_URL,$url);
		curl_setopt($curl,CURLOPT_POST,1);//设置为post请求
		curl_setopt($curl,CURLOPT_POSTFIELDS,$data);//post请求携带的数据
		curl_setopt($curl,CURLOPT_HEADER,0);//不输出返回头信息
		curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);//以文件流的形式返回,而不是直接输出
		curl_setopt($curl,CURLOPT_CONNECTTIMEOUT_MS, 3000);//允许的链接时间  毫秒
		curl_setopt($curl,CURLOPT_TIMEOUT_MS,$timeout);//允许的执行时间
		curl_setopt($curl,CURLOPT_HTTPHEADER,array('X-FORWARDED-FOR:' .$_SERVER['REMOTE_ADDR']));
		$res = curl_exec($curl);
		curl_close($curl);
		return $type?json_decode($res,true):$res;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值