php Curl简单封装

<?php

/**
 * 未详细测试
 * @param unknown $url
 * @param unknown $data = array('name' => 'Foo', 'file' => '@/home/user/test.png'); 
 * @param unknown $config
 * config:
 * 		method
 * 		timeout
 * 		isCookie
 * 		isfollow
 * 		https
 * 		locationUrl
 * @return mixed
 */
function customCurl($url, $data = array(), $config = array()) {
	if (is_array($data)) {
		$data = http_build_query($data);
	}
	
	$ch = curl_init();
	if ($config['method'] == 'post'){
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	}else {
		$url .= '?'.$data;
	}
	
	if ($config['timeout']){
		curl_setopt($ch, CURLOPT_TIMEOUT, $config['timeout']);
	}
	
	if ($config['upFilePath']) {
		curl_setopt($ch, CURLOPT_PUT, 1);
		curl_setopt($ch, CURLOPT_UPLOAD, 1);
		curl_setopt($ch, CURLOPT_INFILE, fopen($config['upFilePath'], 'rb'));
		curl_setopt($ch, CURLOPT_INFILESIZE, filesize($config['upFilePath']));
	}
	
	if ($config['isCookie']){
		date_default_timezone_set('PRC');
		curl_setopt($ch, CURLOPT_COOKIESESSION, true);
		curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookiefile');
		curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookiefile');
		curl_setopt($ch, CURLOPT_COOKIE, session_name().'='.session_id());
	}
	
	if ($config['isfollow'] || $config['isCookie'] || $config['https']){
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	}

	if ($config['https']){
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	}
	
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		'Content-type: application/x-www-form-urlencoded; charset=UTF-8',
		'Content-length: '.strlen($data)
	));
	
	$rtn = curl_exec($ch);
	if (curl_errno($ch)) {
		echo 'Curl errno: '.curl_error($ch);
		curl_close($ch);
	}else {
		//$info = curl_getinfo($ch);
		//print_r($info);
		if ($config['locationUrl']){
			curl_setopt($ch, CURLOPT_URL, $config['locationUrl']);
			curl_setopt($ch, CURLOPT_PORT, 0);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Content-type: application/x-www-form-urlencoded; charset=UTF-8',
			));
			$output = curl_exec($ch);
			if (curl_errno($ch)) {
				echo 'Curl errno: '.curl_error($ch);
				curl_close($ch);
			}
		}
		
		curl_close($ch);
		return $config['locationUrl'] ? $output : $rtn;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值