<?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;
}
}
php Curl简单封装
最新推荐文章于 2022-08-31 17:31:24 发布