在PHP中,我在许多PHP项目中都看到了cURL这个词。是什么?它是如何工作的?
参考链接:cURL
在PHP中,我在许多PHP项目中都看到了cURL这个词。是什么?它是如何工作的?
参考链接:cURL
当前回答
cURL是一种从代码中命中URL以获得html响应的方法。cURL的意思是客户端URL,它允许你与其他URL连接,并在你的代码中使用它们的响应。
其他回答
PHP中的cURL是使用PHP语言中的命令行cURL的桥梁
cURL是一种从代码中命中URL以获得html响应的方法。cURL的意思是客户端URL,它允许你与其他URL连接,并在你的代码中使用它们的响应。
cURL扩展到PHP的目的是让你从你的PHP脚本中使用各种web资源。
Php curl函数(POST,GET,DELETE,PUT)
function curl($post = array(), $url, $token = '', $method = "POST", $json = false, $ssl = true){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
if($method == 'POST'){
curl_setopt($ch, CURLOPT_POST, 1);
}
if($json == true){
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json','Authorization: Bearer '.$token,'Content-Length: ' . strlen($post)));
}else{
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
if($ssl == false){
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
// curl_setopt($ch, CURLOPT_HEADER, 0);
$r = curl_exec($ch);
if (curl_error($ch)) {
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
print_r('Error: ' . $err . ' Status: ' . $statusCode);
// Add error
$this->error = $err;
}
curl_close($ch);
return $r;
}
cURL
cURL是一种从代码中命中URL以从中获得HTML响应的方法。 它用于PHP语言的命令行cURL。 cURL是一个允许您在PHP中发出HTTP请求的库。
PHP支持libcurl,这是Daniel Stenberg创建的库,它允许您使用许多不同类型的协议连接和通信到许多不同类型的服务器。Libcurl目前支持http、https、ftp、gopher、telnet、dict、file和ldap协议。libcurl还支持HTTPS证书、HTTP POST、HTTP PUT、FTP上传(这也可以用PHP的FTP扩展完成)、基于HTTP表单的上传、代理、cookie和用户+密码身份验证。
在编译了支持cURL的PHP之后,就可以开始使用cURL函数了。cURL函数背后的基本思想是使用curl_init()初始化一个cURL会话,然后可以通过curl_setopt()设置传输的所有选项,然后可以使用curl_exec()执行会话,然后使用curl_close()结束会话。
示例代码
// error reporting
error_reporting(E_ALL);
ini_set("display_errors", 1);
//setting url
$url = 'http://example.com/api';
//data
$data = array("message" => "Hello World!!!");
try {
$ch = curl_init($url);
$data_string = json_encode($data);
if (FALSE === $ch)
throw new Exception('failed to initialize');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$output = curl_exec($ch);
if (FALSE === $output)
throw new Exception(curl_error($ch), curl_errno($ch));
// ...process $output now
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
如需更多信息,请查看-
旋度 旋度函数