php curl请求封装(备份,万一下次用到了,直接copy哈哈哈)
2015-10-29 16:11
603 查看
/**
* 发起get或者post请求
* @param string $url Url to request
* @param array $params Parameters for the request
* @param string $httpMethod Http method, 'GET' or 'POST'
* @return string|false Returns string if success, or false if failed
*/
private static function request($url, $params = array(), $httpMethod = 'GET')
{
$ch = curl_init();
$curl_opts = array(
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 5,
CURLOPT_USERAGENT => 'jd',
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => false,
);
if (stripos($url, 'https://') === 0) {
$curl_opts[CURLOPT_SSL_VERIFYPEER] = false;
}
if (strtoupper($httpMethod) === 'GET') {
$query = http_build_query($params, '', '&');
$delimiter = strpos($url, '?') === false ? '?' : '&';
$curl_opts[CURLOPT_URL] = $url . $delimiter . $query;
$curl_opts[CURLOPT_POST] = false;
} else {
$body = http_build_query($params, '', '&');
$curl_opts[CURLOPT_URL] = $url;
$curl_opts[CURLOPT_POSTFIELDS] = $body;
}
curl_setopt_array($ch, $curl_opts);
$result = curl_exec($ch);
curl_close($ch);
if (($result === false) || empty($result)) {
return false;
}
return $result;
}
* 发起get或者post请求
* @param string $url Url to request
* @param array $params Parameters for the request
* @param string $httpMethod Http method, 'GET' or 'POST'
* @return string|false Returns string if success, or false if failed
*/
private static function request($url, $params = array(), $httpMethod = 'GET')
{
$ch = curl_init();
$curl_opts = array(
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 5,
CURLOPT_USERAGENT => 'jd',
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => false,
);
if (stripos($url, 'https://') === 0) {
$curl_opts[CURLOPT_SSL_VERIFYPEER] = false;
}
if (strtoupper($httpMethod) === 'GET') {
$query = http_build_query($params, '', '&');
$delimiter = strpos($url, '?') === false ? '?' : '&';
$curl_opts[CURLOPT_URL] = $url . $delimiter . $query;
$curl_opts[CURLOPT_POST] = false;
} else {
$body = http_build_query($params, '', '&');
$curl_opts[CURLOPT_URL] = $url;
$curl_opts[CURLOPT_POSTFIELDS] = $body;
}
curl_setopt_array($ch, $curl_opts);
$result = curl_exec($ch);
curl_close($ch);
if (($result === false) || empty($result)) {
return false;
}
return $result;
}
相关文章推荐
- PHP开发框架HushFrameword在阿里服务器Windows Server2012上的环境搭建正确方法
- vsftpd本身不支持软连接
- 最准确的php截取字符串长度函数
- TFTP Server 搭建嵌入式
- PHP与.NET一致的DES(CBC)算法
- php关键字仅替换一次的实现函数
- ThinkPHP验证码不现实的处理方法
- php 框架 yii control 中使用布局
- PHP Twig模版的tags详解(中文)
- 深入浅析PHP7.0新特征(五大新特征)
- Ubuntu下安装、配置FTP服务
- PHP 7 值得期待的新特性(上)
- yii的csrf验证
- [Windows Server 2012] IIS自带FTP配置方法
- PHP 7 值得期待的新特性(上)
- vsftp设置不同用户登录ftp的根目录不同
- 用phpmyadimn来连接管理多个数据库
- getOutputStream() has already been called for this response 错误异常的处理
- ubuntu下对php环境的配置步骤
- 适用于初学者的简易PHP文件上传类