php PHP中的cURL是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3062324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is cURL in PHP?
提问by Aakash Chakravarthy
回答by Johannes Gorset
cURLis a library that lets you make HTTP requests in PHP. Everything you need to know about it (and most other extensions) can be found in the PHP manual.
cURL是一个库,可让您在 PHP 中发出 HTTP 请求。您需要了解的有关它(以及大多数其他扩展)的所有信息都可以在PHP 手册 中找到。
In order to use PHP's cURL functions you need to install the ? libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.
为了使用 PHP 的 cURL 函数,您需要安装 ? libcurl 包。PHP 要求您使用 libcurl 7.0.2-beta 或更高版本。在 PHP 4.2.3 中,您需要 libcurl 7.9.0 或更高版本。从 PHP 4.3.0 开始,您将需要 7.9.8 或更高版本的 libcurl。PHP 5.0.0 需要 libcurl 7.10.5 或更高版本。
You can make HTTP requests without cURL, too, though it requires allow_url_fopento be enabled in your php.inifile.
您也可以在没有 cURL 的情况下发出 HTTP 请求,但需要allow_url_fopen在您的php.ini文件中启用它。
// Make a HTTP GET request and print it (requires allow_url_fopen to be enabled)
print file_get_contents('http://www.example.com/');
回答by sushil bharwani
cURL is a way you can hit a URL from your code to get a html response from it. cURL means client URL which allows you to connect with other URLs and use their responses in your code.
cURL 是一种可以从代码中点击 URL 以从中获取 html 响应的方法。cURL 表示客户端 URL,它允许您连接其他 URL 并在您的代码中使用它们的响应。
回答by Eric Leschinski
CURL in PHP:
PHP中的卷曲:
Summary:
概括:
The curl_execcommand in PHP is a bridge to use curlfrom console. curl_exec makes it easy to quickly and easily do GET/POST requests, receive responses from other servers like JSON and download files.
curl_execPHP 中的命令是curl从控制台使用的桥梁。curl_exec 可以轻松快速轻松地执行 GET/POST 请求,从其他服务器(如 JSON)接收响应并下载文件。
Warning, Danger:
警告、危险:
curlis evil and dangerous if used improperly because it is all about getting data from out there in the internet. Someone can get between your curl and the other server and inject a rm -rf /into your response, and then why am I dropped to a console and ls -ldoesn't even work anymore? Because you mis underestimated the dangerous power of curl. Don't trust anything that comes back from curl to be safe, even if you are talking to your own servers. You could be pulling back malware to relieve fools of their wealth.
curl如果使用不当,则是邪恶和危险的,因为这完全是为了从互联网上获取数据。有人可以在您的 curl 和另一台服务器之间插入并将 arm -rf /注入您的响应,然后为什么我会掉到控制台ls -l甚至不再工作?因为你低估了卷曲的危险力量。不要相信从 curl 返回的任何东西都是安全的,即使您正在与自己的服务器交谈。您可能会撤回恶意软件以减轻傻瓜们的财富。
Examples:
例子:
These were done on Ubuntu 12.10
这些是在 Ubuntu 12.10 上完成的
Basic curl from the commandline:
el@apollo:/home/el$ curl http://i.imgur.com/4rBHtSm.gif > mycat.gif % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 492k 100 492k 0 0 1077k 0 --:--:-- --:--:-- --:--:-- 1240kThen you can open up your gif in firefox:
firefox mycat.gifGlorious cats evolving Toxoplasma gondii to cause women to keep cats around and men likewise to keep the women around.
cURL example get request to hit google.com, echo to the commandline:
This is done through the phpsh terminal:
php> $ch = curl_init(); php> curl_setopt($ch, CURLOPT_URL, 'http://www.google.com'); php> curl_exec($ch);Which prints and dumps a mess of condensed html and javascript (from google) to the console.
cURL example put the response text into a variable:
This is done through the phpsh terminal:
php> $ch = curl_init(); php> curl_setopt($ch, CURLOPT_URL, 'http://i.imgur.com/wtQ6yZR.gif'); php> curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); php> $contents = curl_exec($ch); php> echo $contents;The variable now contains the binary which is an animated gif of a cat, possibilities are infinite.
Do a curl from within a PHP file:
Put this code in a file called myphp.php:
<?php $curl_handle=curl_init(); curl_setopt($curl_handle,CURLOPT_URL,'http://www.google.com'); curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2); curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1); $buffer = curl_exec($curl_handle); curl_close($curl_handle); if (empty($buffer)){ print "Nothing returned from url.<p>"; } else{ print $buffer; } ?>Then run it via commandline:
php < myphp.phpYou ran myphp.php and executed those commands through the php interpreter and dumped a ton of messy html and javascript to screen.
You can do
GETandPOSTrequests with curl, all you do is specify the parameters as defined here: Using curl to automate HTTP jobs
命令行中的基本卷曲:
el@apollo:/home/el$ curl http://i.imgur.com/4rBHtSm.gif > mycat.gif % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 492k 100 492k 0 0 1077k 0 --:--:-- --:--:-- --:--:-- 1240k然后你可以在firefox中打开你的gif:
firefox mycat.gif光荣的猫进化出弓形虫,让女人养猫,男人也养女人。
cURL 示例获取访问 google.com 的请求,回显到命令行:
这是通过 phpsh 终端完成的:
php> $ch = curl_init(); php> curl_setopt($ch, CURLOPT_URL, 'http://www.google.com'); php> curl_exec($ch);它将一堆压缩的 html 和 javascript(来自谷歌)打印并转储到控制台。
cURL 示例将响应文本放入变量中:
这是通过 phpsh 终端完成的:
php> $ch = curl_init(); php> curl_setopt($ch, CURLOPT_URL, 'http://i.imgur.com/wtQ6yZR.gif'); php> curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); php> $contents = curl_exec($ch); php> echo $contents;变量现在包含二进制文件,它是猫的动画 gif,可能性是无限的。
从 PHP 文件中执行 curl:
将此代码放在名为 myphp.php 的文件中:
<?php $curl_handle=curl_init(); curl_setopt($curl_handle,CURLOPT_URL,'http://www.google.com'); curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2); curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1); $buffer = curl_exec($curl_handle); curl_close($curl_handle); if (empty($buffer)){ print "Nothing returned from url.<p>"; } else{ print $buffer; } ?>然后通过命令行运行它:
php < myphp.php您运行 myphp.php 并通过 php 解释器执行这些命令,并将大量凌乱的 html 和 javascript 转储到屏幕上。
您可以使用 curl执行
GET和POST请求,您所做的只是指定此处定义的参数:使用 curl 自动执行 HTTP 作业
Reminder of danger:
危险提示:
Be careful dumping curl output around, if any of it gets interpreted and executed, your box is owned and your credit card info will be sold to third parties and you'll get a mysterious $900 charge from an Alabama one-man flooring company that's a front for overseas credit card fraud crime ring.
小心倾倒 curl 输出,如果其中任何一个被解释和执行,你的盒子是拥有的,你的信用卡信息将被出售给第三方,你将从阿拉巴马州的一家单人地板公司获得神秘的 900 美元费用,这是一家海外信用卡诈骗犯罪团伙的前线。
回答by Neha Sinha
cURL is a way you can hit a URL from your code to get a HTML response from it. It's used for command line cURL from the PHP language.
cURL 是一种可以从代码中点击 URL 以从中获取 HTML 响应的方法。它用于来自 PHP 语言的命令行 cURL。
<?php
// Step 1
$cSession = curl_init();
// Step 2
curl_setopt($cSession,CURLOPT_URL,"http://www.google.com/search?q=curl");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
// Step 3
$result=curl_exec($cSession);
// Step 4
curl_close($cSession);
// Step 5
echo $result;
?>
Step 1: Initialize a curl session using curl_init().
步骤 1:使用curl_init().
Step 2: Set option for CURLOPT_URL. This value is the URL which we are sending the request to. Append a search term curlusing parameter q=. Set option for CURLOPT_RETURNTRANSFER. True will tell curl to return the string instead of print it out. Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value.
第 2 步:设置选项CURLOPT_URL。该值是我们将请求发送到的 URL。curl使用参数附加搜索词q=。设置选项CURLOPT_RETURNTRANSFER。True 会告诉 curl 返回字符串而不是打印出来。为 设置选项CURLOPT_HEADER,false 将告诉 curl 忽略返回值中的标头。
Step 3: Execute the curl session using curl_exec().
第 3 步:使用curl_exec().
Step 4: Close the curl session we have created.
第 4 步:关闭我们创建的 curl 会话。
Step 5: Output the return string.
第五步:输出返回字符串。
public function curlCall($apiurl, $auth, $rflag)
{
$ch = curl_init($apiurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if($auth == 'auth') {
curl_setopt($ch, CURLOPT_USERPWD, "passw:passw");
} else {
curl_setopt($ch, CURLOPT_USERPWD, "ss:ss1");
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$dt = curl_exec($ch);
curl_close($ch);
if($rflag != 1) {
$dt = json_decode($dt,true);
}
return $dt;
}
This is also used for authentication. We can also set the username and password for authentication.
这也用于身份验证。我们还可以设置用户名和密码进行身份验证。
For more functionality, see the user manual or the following tutorial:
有关更多功能,请参阅用户手册或以下教程:
http://php.net/manual/en/ref.curl.php
http://www.startutorial.com/articles/view/php-curl
http://php.net/manual/en/ref.curl.php
http://www.startutorial.com/articles/view/php-curl
回答by Anand Pandey
Firstly let us understand the concepts of curl, libcurl and PHP/cURL.
首先让我们了解curl、libcurl和PHP/cURL的概念。
curl: A command line tool for getting or sending files using URL syntax.
libcurl: a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
PHP/cURL: The module for PHP that makes it possible for PHP programs to use libcurl.
curl:使用 URL 语法获取或发送文件的命令行工具。
libcurl:一个由 Daniel Stenberg 创建的库,它允许您使用许多不同类型的协议连接和通信到许多不同类型的服务器。libcurl 目前支持 http、https、ftp、gopher、telnet、dict、file 和 ldap 协议。libcurl 还支持 HTTPS 证书、HTTP POST、HTTP PUT、FTP 上传(这也可以通过 PHP 的 ftp 扩展完成)、基于 HTTP 表单的上传、代理、cookie 和用户+密码验证。
PHP/cURL:PHP 模块,使 PHP 程序可以使用 libcurl。
How to use it:
如何使用它:
step1: Initialize a curl session use curl_init().
step1:使用 curl_init() 初始化 curl 会话。
step2: Set option for CURLOPT_URL. This value is the URL which we are sending the request to.Append a search term "curl" using parameter "q=".Set option CURLOPT_RETURNTRANSFER, true will tell curl to return the string instead ofprint it out. Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value.
step2: 为 CURLOPT_URL 设置选项。该值是我们将请求发送到的 URL。使用参数“q=”附加搜索词“curl”。设置选项 CURLOPT_RETURNTRANSFER,true 将告诉 curl 返回字符串而不是打印出来。为 CURLOPT_HEADER 设置选项,false 将告诉 curl 忽略返回值中的标头。
step3: Execute the curl session using curl_exec().
step3:使用 curl_exec() 执行 curl 会话。
step4: Close the curl session we have created.
step4:关闭我们创建的curl会话。
step5: Output the return string.
step5:输出返回字符串。
Make DEMO:
制作演示:
You will need to create two PHP files and place them into a folder that your web server can serve PHP files from. In my case I put them into /var/www/ for simplicity.
您将需要创建两个 PHP 文件并将它们放入您的 Web 服务器可以从中提供 PHP 文件的文件夹中。就我而言,为了简单起见,我将它们放入 /var/www/ 中。
1. helloservice.phpand 2. demo.php
1. helloservice.php和2. demo.php
helloservice.php is very simple and essentially just echoes back any data it gets:
helloservice.php 非常简单,本质上只是回显它获得的任何数据:
<?php
// Here is the data we will be sending to the service
$some_data = array(
'message' => 'Hello World',
'name' => 'Anand'
);
$curl = curl_init();
// You can also set the URL you want to communicate with by doing this:
// $curl = curl_init('http://localhost/echoservice');
// We POST the data
curl_setopt($curl, CURLOPT_POST, 1);
// Set the url path we want to call
curl_setopt($curl, CURLOPT_URL, 'http://localhost/demo.php');
// Make it so the data coming back is put into a string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Insert the data
curl_setopt($curl, CURLOPT_POSTFIELDS, $some_data);
// You can also bunch the above commands into an array if you choose using: curl_setopt_array
// Send the request
$result = curl_exec($curl);
// Get some cURL session information back
$info = curl_getinfo($curl);
echo 'content type: ' . $info['content_type'] . '<br />';
echo 'http code: ' . $info['http_code'] . '<br />';
// Free up the resources $curl is using
curl_close($curl);
echo $result;
?>
2.demo.phppage, you can see the result:
2.demo.php页面,可以看到结果:
<?php
print_r($_POST);
//content type: text/html; charset=UTF-8
//http code: 200
//Array ( [message] => Hello World [name] => Anand )
?>
回答by Naved Ahmed
The cURL extension to PHP is designed to allow you to use a variety of web resources from within your PHP script.
PHP 的 cURL 扩展旨在允许您从 PHP 脚本中使用各种 Web 资源。
回答by Jaime Hablutzel
cURL in PHP is a bridge to use command line cURL from the php language
PHP 中的 cURL 是使用来自 php 语言的命令行 cURL 的桥梁
回答by Joomler
cURL
卷曲
- cURL is a way you can hit a URL from your code to get a HTML response from it.
- It's used for command line cURL from the PHP language.
- cURL is a library that lets you make HTTP requests in PHP.
- cURL 是一种可以从代码中点击 URL 以从中获取 HTML 响应的方法。
- 它用于来自 PHP 语言的命令行 cURL。
- cURL 是一个库,可让您在 PHP 中发出 HTTP 请求。
PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
PHP 支持 libcurl,这是一个由 Daniel Stenberg 创建的库,它允许您使用许多不同类型的协议连接和通信到许多不同类型的服务器。libcurl 目前支持 http、https、ftp、gopher、telnet、dict、file 和 ldap 协议。libcurl 还支持 HTTPS 证书、HTTP POST、HTTP PUT、FTP 上传(这也可以通过 PHP 的 ftp 扩展完成)、基于 HTTP 表单的上传、代理、cookie 和用户+密码验证。
Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close().
一旦您编译了支持 cURL 的 PHP,您就可以开始使用 cURL 函数了。cURL 函数背后的基本思想是您使用 curl_init() 初始化 cURL 会话,然后您可以通过 curl_setopt() 设置传输的所有选项,然后您可以使用 curl_exec() 执行会话,然后您使用 curl_close() 结束您的会话。
Sample Code
示例代码
// 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);
}
For more information, please check -
欲了解更多信息,请检查 -
回答by Ankur Kumar Singh
Curl is nothing but an extension of PHP which inherits behaviors of the normal curl command & library written primarily for Linux/Unix command line tool
curl 只不过是 PHP 的扩展,它继承了主要为 Linux/Unix 命令行工具编写的普通 curl 命令和库的行为
What is Curl?cURL stand for Client URL. The cURL is used to send data to any URL. For more detail about what curl exactly is, you can visit CURL Website
什么是卷曲?cURL 代表客户端 URL。cURL 用于将数据发送到任何 URL。有关 curl 究竟是什么的更多详细信息,您可以访问CURL 网站
cURL in PHP Now the same concept is introduced in PHP, to send data to any accessible URL via the different protocol, for example, HTTP or FTP. For More detail, you may refer to PHP Curl Tutorial
PHP 中的 cURL 现在 PHP 中引入了相同的概念,通过不同的协议将数据发送到任何可访问的 URL,例如 HTTP 或 FTP。更详细的可以参考PHP Curl 教程
回答by Ma?yMiszcz
Php curl function (POST,GET,DELETE,PUT)
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;
}

