首先来说以下curl
CURL是一个非常强大的开源库,支持很多协议,包括HTTP、FTP、TELNET等,我们使用它来发送HTTP请求。它给我 们带来的好处是可以通过灵活的选项设置不同的HTTP协议参数,并且支持HTTPS。CURL可以根据URL前缀是“HTTP” 还是“HTTPS”自动选择是否加密发送内容。
但是有时候只用一些简单的操作需要进行复杂的配置,这里只用封装成一个函数就可以解决配置的麻烦了。
/**
* curl函数
* @param string $url 访问地址
* @param array|null $post post参数
* @param int $time 超时时间
* @param string|null $type post类型
* @return bool|string 返回收到的结果
* @author An Yang
* @time 2020/7/7 20:05
*/
function curl(string $url, array $post = NULL, int $time = 30, string $type = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $time);
if (stripos($url, "https://") !== FALSE) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
if (isset($post)) { // post数据
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
if (isset($type)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/' . $type]);
}
}
$output = curl_exec($ch);
curl_close($ch);
return $output;
}第一个参数为网址,第二个参数为需要post的数组,可以为空。
使用例子
如果不使用post,直接用get就可以不用第二个参数
echo curl("http://blog.7cuu.com");如果需要post,那第二个参数就需要带上post的数组了
$post = array(
'username' => 'admin',
'password' => 'admin'
);
echo curl("http://blog.7cuu.com",$post);这样就可以了。
转载请注明:七彩悠悠博客 | 心悠悠 情悠悠 » 常用自定义函数之curl

