简体   繁体   English

PHP中的cURL是什么?

[英]What is cURL in PHP?

In PHP, I see the word cURL in many PHP projects.在 PHP 中,我在许多 PHP 项目中看到 cURL 一词。 What is it?它是什么? How does it work?它是如何工作的?

Reference Link: cURL参考链接: cURL

cURL is a library that lets you make HTTP requests in PHP. cURL是一个允许您在PHP中发出HTTP请求的库。 Everything you need to know about it (and most other extensions) can be found in the PHP manual . 您需要了解的所有内容(以及大多数其他扩展)都可以在PHP手册中找到。

In order to use PHP's cURL functions you need to install the » libcurl package. 要使用PHP的cURL函数,您需要安装»libcurl包。 PHP requires that you use libcurl 7.0.2-beta or higher. PHP要求您使用libcurl 7.0.2-beta或更高版本。 In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. 在PHP 4.2.3中,您将需要libcurl版本7.9.0或更高版本。 From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. 从PHP 4.3.0开始,您需要一个7.9.8或更高版本的libcurl版本。 PHP 5.0.0 requires a libcurl version 7.10.5 or greater. PHP 5.0.0需要libcurl版本7.10.5或更高版本。

You can make HTTP requests without cURL, too, though it requires allow_url_fopen to be enabled in your php.ini file. 您也可以在没有cURL的情况下发出HTTP请求,但它需要在php.ini文件中启用allow_url_fopen

// Make a HTTP GET request and print it (requires allow_url_fopen to be enabled)
print file_get_contents('http://www.example.com/');

cURL is a way you can hit a URL from your code to get a html response from it. cURL是一种可以从代码中获取URL以从中获取html响应的方法。 cURL means client URL which allows you to connect with other URLs and use their responses in your code. cURL表示客户端URL,允许您与其他URL连接并在代码中使用其响应。

CURL in PHP: PHP中的CURL:

Summary: 摘要:

The curl_exec command in PHP is a bridge to use curl from console. PHP中的curl_exec命令是从控制台使用curl的桥梁。 curl_exec makes it easy to quickly and easily do GET/POST requests, receive responses from other servers like JSON and download files. curl_exec可以轻松快速轻松地执行GET / POST请求,接收来自其他服务器(如JSON)和下载文件的响应。

Warning, Danger: 警告,危险:

curl is evil and dangerous if used improperly because it is all about getting data from out there in the internet. 如果使用不当, curl是邪恶和危险的,因为它只是从互联网上获取数据。 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 -l doesn't even work anymore? 有人可以介入你的curl和其他服务器之间并在你的响应中注入一个rm -rf / ,然后为什么我会掉到一个控制台而ls -l甚至不再工作了? 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. 你可能会撤回恶意软件以减轻他们财富的愚蠢。

Examples: 例子:

These were done on Ubuntu 12.10 这些是在Ubuntu 12.10上完成的

  1. 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 --:--:-- --:--:-- --:--:-- 1240k 

    Then you can open up your gif in firefox: 然后你可以在firefox中打开你的gif:

     firefox mycat.gif 

    Glorious cats evolving Toxoplasma gondii to cause women to keep cats around and men likewise to keep the women around. 光荣的猫进化弓形虫,使女性养猫,男人同样保持女性。

  2. cURL example get request to hit google.com, echo to the commandline: cURL示例获取请求到google.com,回显到命令行:

    This is done through the phpsh terminal: 这是通过phpsh终端完成的:

     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. 其中打印并将一堆浓缩的html和javascript(从谷歌)转储到控制台。

  3. cURL example put the response text into a variable: cURL示例将响应文本放入变量:

    This is done through the phpsh terminal: 这是通过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; 

    The variable now contains the binary which is an animated gif of a cat, possibilities are infinite. 变量现在包含二进制文件,它是猫的动画GIF,可能性是无限的。

  4. Do a curl from within a PHP file: 从PHP文件中做一个卷曲:

    Put this code in a file called myphp.php: 将此代码放在名为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.php 

    You ran myphp.php and executed those commands through the php interpreter and dumped a ton of messy html and javascript to screen. 你运行myphp.php并通过php解释器执行这些命令,并将大量凌乱的html和javascript转储到屏幕上。

    You can do GET and POST requests with curl, all you do is specify the parameters as defined here: Using curl to automate HTTP jobs 您可以使用curl执行GETPOST请求,您只需指定此处定义的参数: 使用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. 小心倾倒卷曲输出,如果任何一个被解释和执行,你的盒子是拥有的,你的信用卡信息将出售给第三方,你将得到一个神秘的900美元从阿拉巴马州单人地板公司收取的费用是一个前海外信用卡诈骗犯罪集团。

cURL is a way you can hit a URL from your code to get a HTML response from it. cURL是一种可以从代码中获取URL以从中获取HTML响应的方法。 It's used for command line cURL from the PHP language. 它用于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 . 第2步:为CURLOPT_URL设置选项。 This value is the URL which we are sending the request to. 此值是我们向其发送请求的URL。 Append a search term curl using parameter q= . 使用参数q=附加搜索词curl Set option for CURLOPT_RETURNTRANSFER . 设置CURLOPT_RETURNTRANSFER选项。 True will tell curl to return the string instead of print it out. True将告诉curl返回字符串而不是打印出来。 Set option for CURLOPT_HEADER , false will tell curl to ignore the header in the return value. CURLOPT_HEADER设置选项,false将告诉curl忽略返回值中的标题。

Step 3: Execute the curl session using curl_exec() . 第3步:使用curl_exec()执行curl会话。

Step 4: Close the curl session we have created. 第4步:关闭我们创建的卷曲会话。

Step 5: Output the return string. 第5步:输出返回字符串。

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://php.net/manual/en/ref.curl.php
http://www.startutorial.com/articles/view/php-curl http://www.startutorial.com/articles/view/php-curl

Firstly let us understand the concepts of curl, libcurl and PHP/cURL. 首先让我们理解curl,libcurl和PHP / cURL的概念。

  1. curl : A command line tool for getting or sending files using URL syntax. curl :用于使用URL语法获取或发送文件的命令行工具。

  2. 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 :由Daniel Stenberg创建的库,允许您使用许多不同类型的协议连接和通信到许多不同类型的服务器。 libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl目前支持http,https,ftp,gopher,telnet,dict,file和ldap协议。 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. libcurl还支持HTTPS证书,HTTP POST,HTTP PUT,FTP上传(这也可以使用PHP的ftp扩展),基于HTTP表单的上传,代理,cookie和用户+密码验证。

  3. PHP/cURL : The module for PHP that makes it possible for PHP programs to use libcurl. PHP / cURLPHP的模块,使PHP程序可以使用libcurl。

How to use it: 如何使用它:

step1 : Initialize a curl session use curl_init(). step1 :使用curl_init()初始化卷曲会话。

step2 : Set option for CURLOPT_URL. step2 :设置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. 这个值是我们发送请求的URL。使用参数“q =”添加搜索词“curl”。设置选项CURLOPT_RETURNTRANSFER,true将告诉curl返回字符串而不是将其打印出来。 Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value. 为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. 您需要创建两个PHP文件并将它们放入Web服务器可以从中提供PHP文件的文件夹中。 In my case I put them into /var/www/ for simplicity. 在我的情况下,我将它们放入/ var / www /中以简化。

1. helloservice.php and 2. demo.php 1. helloservice.php2. 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.php page, 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 )
?>

PHP的cURL扩展旨在允许您在PHP脚本中使用各种Web资源。

PHP中的cURL是使用php语言的命令行cURL的桥梁

cURL 卷曲

  • cURL is a way you can hit a URL from your code to get a HTML response from it. cURL是一种可以从代码中获取URL以从中获取HTML响应的方法。
  • It's used for command line cURL from the PHP language. 它用于PHP语言的命令行cURL。
  • cURL is a library that lets you make HTTP requests in PHP. 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. PHP支持libcurl,这是一个由Daniel Stenberg创建的库,它允许您使用许多不同类型的协议连接和通信许多不同类型的服务器。 libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl目前支持http,https,ftp,gopher,telnet,dict,file和ldap协议。 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. 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. 一旦使用cURL支持编译PHP,就可以开始使用cURL函数了。 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函数背后的基本思想是使用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 - 有关更多信息,请检查 -

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. cURL代表客户端URL。 The cURL is used to send data to any URL. cURL用于将数据发送到任何URL。 For more detail about what curl exactly is, you can visit CURL Website 有关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. PHP中的cURL现在PHP中引入了相同的概念,通过不同的协议(例如HTTP或FTP)将数据发送到任何可访问的URL。 For More detail, you may refer to PHP Curl Tutorial 有关更多详细信息,请参阅PHP Curl Tutorial

Php curl class (GET,POST,FILES UPLOAD, SESSIONS, SEND POST JSON, FORCE SELFSIGNED SSL/TLS): Php curl课程(GET,POST,FILES UPLOAD,SESSIONS,SEND POST JSON,FORCE SELFSIGNED SSL / TLS):

<?php
    // Php curl class
    class Curl {

        public $error;

        function __construct() {}

        function Get($url = "http://hostname.x/api.php?q=jabadoo&txt=gin", $forceSsl = false,$cookie = "", $session = true){
            // $url = $url . "?". http_build_query($data);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);        
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){            
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            $info = curl_getinfo($ch);
            $res = curl_exec($ch);        
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            }        
        }

        function GetArray($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $forceSsl = false, $cookie = "", $session = true){
            $url = $url . "?". http_build_query($data);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            $info = curl_getinfo($ch);
            $res = curl_exec($ch);        
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            }        
        }

        function PostJson($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $forceSsl = false, $cookie = "", $session = true){
            $data = json_encode($data);
            $ch = curl_init($url);                                                                      
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);                                                                  
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Authorization: Bearer helo29dasd8asd6asnav7ffa',                                                      
                'Content-Type: application/json',                                                                                
                'Content-Length: ' . strlen($data))                                                                       
            );        
            $res = curl_exec($ch);
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            } 
        }

        function Post($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $files = array('ads/ads0.jpg', 'ads/ads1.jpg'), $forceSsl = false, $cookie = "", $session = true){
            foreach ($files as $k => $v) {
                $f = realpath($v);
                if(file_exists($f)){
                    $fc = new CurlFile($f, mime_content_type($f), basename($f)); 
                    $data["file[".$k."]"] = $fc;
                }
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");        
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); // !!!! required as of PHP 5.6.0 for files !!!
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)");
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            $res = curl_exec($ch);
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            } 
        }
    }
?>

Example: 例:

<?php
    $urlget = "http://hostname.x/api.php?id=123&user=bax";
    $url = "http://hostname.x/api.php";
    $data = array("name" => "Max", "age" => "36");
    $files = array('ads/ads0.jpg', 'ads/ads1.jpg');

    $curl = new Curl();
    echo $curl->Get($urlget, true, "token=12345");
    echo $curl->GetArray($url, $data, true);
    echo $curl->Post($url, $data, $files, true);
    echo $curl->PostJson($url, $data, true);
?>

Php file: api.php Php文件:api.php

<?php
    /*
    $Cookie = session_get_cookie_params();
    print_r($Cookie);
    */
    session_set_cookie_params(9000, '/', 'hostname.x', isset($_SERVER["HTTPS"]), true);
    session_start();

    $_SESSION['cnt']++;
    echo "Session count: " . $_SESSION['cnt']. "\r\n";
    echo $json = file_get_contents('php://input');
    $arr = json_decode($json, true);
    echo "<pre>";
    if(!empty($json)){ print_r($arr); }
    if(!empty($_GET)){ print_r($_GET); }
    if(!empty($_POST)){ print_r($_POST); }
    if(!empty($_FILES)){ print_r($_FILES); }
    // request headers
    print_r(getallheaders());
    print_r(apache_response_headers());
    // Fetch a list of headers to be sent.
    // print_r(headers_list());
?>

Php curl function (POST,GET,DELETE,PUT) Php卷曲功能(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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM