场景:在调用第三方接口时经常需要使用到curl进行数据交互,在初次使用时遇到一些小问题,记录下来随时查阅。

封装curl相关方法便于使用,方法如下:

/**
* @param $url
* @param string $error
* @param array|string $post
* @param int $timeout
* @param null $ref
* @param string $ua
* @param $contentType
* @return bool|mixed
*/
function xcurl($url, &$error = "", $post = array(), $timeout = 5, $ref = null, $ua = "Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre", $contentType) {
$ch = curl_init(); if(!empty($ref)) {
curl_setopt($ch, CURLOPT_REFERER, $ref);
} curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); if (false !== stripos($url, "https://")) { # https处理,不校验相关证书
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
} if(!empty($ua)) {
curl_setopt($ch, CURLOPT_USERAGENT, $ua);
} if(count($post) > 0){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
} if ('json' == $contentType) {
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($post)));
} $output = curl_exec($ch);
if ($output === false) {
$error = curl_error($ch);
curl_close($ch);
return false;
} else {
curl_close($ch);
return $output;
}
}

调用如下:

<?

$url = 'localhost/php/server.php';
$error = '';
$post = [
'hello' => 'world',
'lang' => 'php',
];
$post = json_encode($post); $result = xcurl($url,$error, $post, 5, null, 'Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre', 'json'); var_dump($result);

本地服务接受参数时遇到了问题,无论$_POST还是$_REQUEST都无法获取curl客户端发送的json,所以改用file_get_contents来获取,代码:

print_r(file_get_contents('php://input'));

最终请求curl.php获取到结果为:

/code/php/curl.php:19:string

 '{"hello":"world","lang":"php"}' (length=30)

最新文章

  1. Sublime text 3 快捷键的使用
  2. Javascript权威指南——第一章Javascript概述
  3. pycharm Working directory error
  4. 一份Java学习路线图
  5. About Webkit
  6. new date() 函数在浏览器中的兼容问题!!
  7. [TypeScript] Avoid any type
  8. poj_3468: A Simple Problem with Integers (树状数组区间更新)
  9. JavaScript入门(三)
  10. Java实用知识记录 —— 截止到Java8
  11. 第 10 章 容器监控 - 078 - Docker 最常用的监控方案
  12. struts1与struts2的区别。
  13. VMWare安装
  14. Java:ConcurrentLinkedQueue的实现原理分析
  15. The META for Mobile terminal
  16. pselect 函数
  17. 使用PHP+Sphinx建立高效的站内搜索引擎
  18. loj#2721. 「NOI2018」屠龙勇士
  19. Oracle开发者守则
  20. 打印系统所有的PID

热门文章

  1. Java笔记5:单例模式
  2. 简单工厂模式 SimpleFactory
  3. IOS Appstore价格表
  4. 用.net installshield打包程序时注册第三方控件
  5. &lt;转&gt;windows下编译lua源码
  6. Android.KungFu手机病毒原理及清理方法
  7. nginx 404重定向到自定义页面
  8. Linux中如何配置IP
  9. Effective C++ 条款47
  10. Atitit.互联网 软件编程 数据库方面 架构 大牛 牛人 attilax总结