The CURL library in PHP

Source: Internet
Author: User
Tags http authentication
This article introduces you to the content of PHP in the CURL Library, now share to everyone, the need for friends can refer to

Overview

Brief introduction

At the beginning of the design, CURL (Client URL Library) is a command-line tool that transmits data using URL syntax. With the CURL library, we can freely use some kind of protocol in PHP scripts to get or submit data, such as getting HTTP request data. In simple terms, CURL is a tool for clients to request resources from the server.

PHP supports the Libcurl library created by Daniel Stenberg, capable of connecting various servers and using various protocols. Libcurl currently supports protocols such as HTTP, HTTPS, FTP, Gopher, Telnet, dict, file, LDAP. Libcurl also supports HTTPS certificate, HTTP POST, HTTP PUT, FTP upload (also can be done via PHP FTP extension), HTTP based on form upload, proxy, cookies, username + password Authentication.

Advantage

In PHP, it is very simple to get the content of a URL, there are many implementations, such as using a file_get_contents() function:

<?php$content = file_get_contents ("https://segmentfault.com"); Var_dump ($content);

Although the file_get_contents() functions are convenient to use, they are not flexible enough to handle errors. In some complex requests, can not set the request header, Cookie, proxy, authentication and other related information, not to a server to submit form data, upload files.

The CURl library not only supports rich network protocols, but also provides a powerful way to set up various URL request parameters. There are many usage scenarios for CURL, such as accessing Web resources, obtaining WebService interface data, and downloading FTP server files.

Use

Basic steps

To use CURL to send a URL request, the step is broadly divided into the following four steps:

    1. Initializes a CURL session;

    2. Set request options;

    3. Perform a CURL session;

    4. Close the CURL session.

1. Initialize the CURL session $ch = Curl_init ();//2. Set request Options curl_setopt ($ch, Curlopt_url, "https://segmentfault.com"); curl_setopt ($ch, Curlopt_returntransfer, TRUE); # The information obtained is returned as a string instead of the direct output curl_setopt ($ch, Curlopt_ssl_verifypeer, 0); # Disable CURL to validate peer certificates, which supports HTTPS access//3. Perform a cURL session $response = Curl_exec ($ch); Var_dump ($response);//4. Turn off CURL session curl_close ($CH);
CURL mainly through curl_setopt() the function to set the request option, the specific description of each option see Http://php.net/manual/zh/func
...

Error handling

curl_error()The function allows you to view the details of the CURL session error, and the curl_getinfo() function can view the response information. Therefore, we can implement a simple error handler through these two functions, for example, we now access a nonexistent URL address:

<?php//1. Initialize the CURL session $ch = Curl_init ();//2. Set request Options curl_setopt ($ch, Curlopt_url, "https://segmentfault.com/test.php"); curl_setopt ($ch, Curlopt_returntransfer, 1); # The information obtained is returned as a string instead of the direct output curl_setopt ($ch, Curlopt_ssl_verifypeer, 0); # Disable CURL to validate peer certificates, which supports HTTPS access//3. Perform a cURL session $response = Curl_exec ($ch), if ($response  = = = FALSE) {    echo "CURL Connert error:". Curl_error ($ch);    Exit;} $info = Curl_getinfo ($ch), if ($info [' http_code '] = = 404) {    echo ' http 404 ';    Exit;} Var_dump ($response);//4. Turn off CURL session curl_close ($CH);

Practical cases

1. POST Request

To send a POST request using CURL impersonation:

<?phpfunction curl_post ($url, $data) {    $ch = Curl_init ();     Curl_setopt_array ($ch, [        curlopt_url = $url,        curlopt_returntransfer = 1, # Gets the information returned as a string        curlopt_ Post # = 1,           # Send POST request        Curlopt_postfields + = $data, # POST request data     ]);    $response = curl_exec ($ch);        Curl_close ($ch);        return $response;} $url  = ' http://localhost/test.php '; $data = [' id ' = = 1, ' username ' = ' jochen '];echo curl_post ($url, $data);

2. File Upload

Curlopt_postfields: All data is sent using the "POST" action in the HTTP protocol. To send a file, precede the file name with the @ prefix and use the full path. The file type can be specified in the format '; Type=mimetype ' after the file name. This parameter can be a string after urlencoded, similar to ' Val1=1&val2=2& ... ', or you can use an array with field names as key values and field data as values.

Send a POST request via CURL for file upload:

<?phpfunction curl_upload ($url, $data) {    $ch = Curl_init ();     Curl_setopt_array ($ch, [        curlopt_url = $url,        curlopt_returntransfer = 1, # Gets the information returned as a string        curlopt_ Post # = 1,           # Send POST request        Curlopt_postfields + = $data, # POST request data     ]);    $response = curl_exec ($ch);        Curl_close ($ch);        return $response;} $url  = ' http://localhost/test.php '; $data = [' id ' = = 1, ' file ' = ' @/root/image/boy.jpg '];echo curl_post ($url , $data);

3. File download

In fact, the file download is the same as the normal GET request, except that the file download saves the returned content to the file instead of the simple output. Matching file_put_contents() functions for file download:

<?phpfunction curl_download ($url, $path) {    $ch = Curl_init ();     Curl_setopt_array ($ch, [        curlopt_url = $url,        curlopt_returntransfer = 1, # Gets the information returned as a string    ]);    $response = curl_exec ($ch);        Curl_close ($ch);        Return file_put_contents ($path, $response);} Curl_download (' http://localhost/boy.jpg ', './boy.jpg ');

4. HTTP Authentication

If the server side needs to verify the request, set the CURLOPT_USERPWD parameters:

<?phpfunction Curl_auth ($url, $user, $passwd) {    $ch = Curl_init ();        Curl_setopt_array ($ch, [        curlopt_url = $url,        curlopt_userpwd = "$user: $passwd", # in the format: "[username]:[ Password] "        Curlopt_returntransfer + 1    ]);        $result = curl_exec ($ch);        Curl_close ($ch);        return $result;} echo Curl_auth (' http://localhost ', ' Jochen ', ' password ');

5. Analog Login

The

Here mainly shows the app that simulates login using cookies to keep the login state. First we need to log in with the account password to obtain the cookie data, and then use the logged in cookie to obtain the page data:

<?php//Analog Login Get cookiefunction curl_login ($url, $data, $cookie) {$ch = Curl_init (); Curl_setopt_array ($ch, [Curlopt_url = $url, curlopt_post = 1, # Send a POST request curlopt _postfields = # $data, # POST request Data Curlopt_cookiejar = # $cookie # Save cookie information to a file Curlopt_returntran    Sfer = 1, # Gets the information returned as a string]);        $response = curl_exec ($ch);        Curl_close ($ch); return $response;}         Gets the page data function curl_content ($url, $cookie) {$ch = Curl_init ();        Curl_setopt_array ($ch, [Curlopt_url = $url, curlopt_cookiefile = $cookie # Load a file containing cookie data    Curlopt_returntransfer = 1, # Gets the information returned as a string]);        $response = curl_exec ($ch);        Curl_close ($ch); return $response;} $post = [' username ' = ' jochen ', ' password ' = ' 123456 ']; $cookie = './cookie.txt '; if (Curl_login (' http://localhost /login ', $post, $cookie) {echo curl_content (' http://localhost ', $cookie);}

CURL Package Library

PHP Curl Class is a well-written Curl wrapper library that makes it very easy to send HTTP requests and integrate with any type of Web API. PHP Curl Class Wrapper library for PHP 5.3,5.4,5.5,5.6,7.0,7.1 and HHVM. This library is well known and provides a very simple syntax:

<?phprequire __dir__. '/vendor/autoload.php '; use \curl\curl; $curl = new Curl (); $curl->get (' https://www.example.com/'); if ($curl Error) {    echo ' ERROR: '. $curl->errorcode. ': ' . $curl->errormessage. "\ n";} else {    echo ' Response: '. "\ n";    Var_dump ($curl->response);}

Reference article:

    1. Client URL Library

    2. Getting Started tutorials and common usage examples for curl in PHP

    3. Using Curl in PHP, "tease" the server just a few lines--php curl detailed parsing and common pits

    4. Top 7:best Curl Wrapper Libraries for PHP


Related recommendations:

PHP concurrency with Curl reduces back-end access time

php log in with curl and get data

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.