PHP with Curl in PHP curl detailed parsing and common pits

Source: Internet
Author: User
Tags curl options http authentication http post set cookie ssl certificate
This article mainly introduces PHP using curl in the detailed analysis of Php curl and common pits, and now share to everyone, but also for everyone to make a reference. Let's take a look at it with a little knitting.

Tanabata, as a development, sister did not have to tease "tease" down the server bar, sister have to tease the classmate that left hug sister right embrace server bar, moreover sister is to gift, server and not. All right, long story short,--curl the tool of today (Client URL Library), of course, today, using PHP as the tool.

0. What's a curl?

PHP supports Libcurl, a library created by Daniel Stenberg, which allows you to connect and communicate to many different T Ypes 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 is done with PHP ' s FTP extensi On), HTTP form based upload, proxies, cookies, and User+password authentication.

This is a PHP explanation for curl, in short, curl is a library that allows you to hook up, chat, and get in-depth with URLs and many different kinds of servers, and also supports many protocols. And they also said that curl can support HTTPS authentication, HTTP POST, FTP upload, agent, cookies, simple password authentication and so on.

Said so much actually no feeling, in the application has the feeling, I also need to start a POST request on the server side to another server to begin to touch curl, and then have the feeling.

In the formal talk about how to use before Ah, first of all, you have to install and enable the Curl module in your PHP environment, the specific way I do not say, different systems, different installation methods, Google can check, or check the official PHP document, is quite simple.

1. Try hackers first.

Tools hand, first to play, try to smooth, or a take to use, your own code to make a mess of how to go to the server?

For example, we use the famous "test network is connected" site-Baidu, for example, to try to curl

<?php     //Create curl resource    $ch = Curl_init ();    Set URL    curl_setopt ($ch, Curlopt_url, "baidu.com");    Return the transfer as a string    curl_setopt ($ch, Curlopt_returntransfer, 1);    $output contains the output string    $output = curl_exec ($ch);     echo Output    echo $output;   Close Curl resource to free up system resources    curl_close ($ch);      ? >

When you open this PHP file in the local environment browser, the page appears is Baidu's homepage, special I just entered the "localhost"?

The code and comments above have amply explained what this code is doing.

$ch = curl_init(), a Curl session resource was created and a handle was successfully returned;
curl_setopt($ch, CURLOPT_URL, "baidu.com"), set the URL, needless to say;

The above two sentences can be combined to change a sentence $ch = curl_init("baidu.com") ;

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0)This is set whether the response result is stored in a variable, 1 is deposited, 0 is the direct echo out;

$output = curl_exec($ch)execution, and then the response results are stored $output in variables for the following echo;

curl_close($ch)Close this Curl session resource.

The use of curl in PHP is roughly a form, where the second step, through the curl_setopt method to set parameters is the most complex is the most important , interested can go to see the official on the parameters of the detailed reference, long to let you see to vomit, or according to the need to make perfect.

To summarize, the Curl usage in PHP is: Create a Curl session, configure parameters, and so on to perform a shutdown session.

Let's take a look at some common scenarios where we need to "dress up" (configuration parameters) in order to properly "tease the sister" (right to the server).

2. Hello--get and POST requests and HTTPS protocol processing

Say hello to the server first, send a hello to the server to see how she returns, here the most convenient way is to send a GET request to the server, of course, post this small note is OK.

2.1 GET Request

For example, "search for a keyword in GitHub, a well-known gay dating site"

Case of Get request via Curl <?php     //Create curl resource    $ch = Curl_init ();    Set URL    curl_setopt ($ch, Curlopt_url, "https://github.com/search?q=react");    Return the transfer as a string    curl_setopt ($ch, Curlopt_returntransfer, 1);    $output contains the output string    $output = curl_exec ($ch);    echo Output   echo $output;   Close Curl resource to free up system resources    curl_close ($ch);      ? >

It seems to be no different from the previous example, but here are 2 points to ask:
1. The default request method is get, so you do not need to explicitly specify the get mode;
2.HTTPS request, non-HTTP request, someone may have seen in various places HTTPS request need to add a few lines of code to bypass the SSL certificate check and other ways to successfully request to the resource, but this does not seem to need, why?

The both Curl options are defined as:

Curlopt_ssl_verifypeer-verify The peer ' s SSL certificate  curlopt_ssl_verifyhost-verify The certificate ' s name Aga Inst Host

They both default to true in Curl, and shouldn ' t is disabled unless you ' ve got a good reason. Disabling them is generally-needed if you ' re sending requests-servers with invalid or self-signed certificates, WH Ich is only usually a issue in development. Any publicly-facing site should is presenting a valid certificate, and by disabling these options you ' re potentially openi Ng yourself up to security issues.

That is, unless you use illegal or self-made certificates, most of which appear in the development environment, you set these two lines to false avoid SSL certificate checking, no one does not need to do so, it is unsafe to do so.

2.2 POST Request

So how do I make a POST request? For testing, a script that receives a post is first passed to a test server:

testrespond.php<?php      $phpInput =file_get_contents (' php://input ');    echo UrlDecode ($phpInput);? >

Send normal data

Then write a request locally:

<?php     $data =array (    "Name" = "Lei",    "msg" = "Is you OK?"    );    $ch = Curl_init ();     curl_setopt ($ch, Curlopt_url, "http://test server IP mosaic/testrespond.php");     curl_setopt ($ch, Curlopt_post, 1);    The number of seconds to wait while trying to connect. Use the 0 to wait indefinitely.    curl_setopt ($ch, Curlopt_connecttimeout,);     curl_setopt ($ch, Curlopt_postfields, Http_build_query ($data));    curl_setopt ($ch, Curlopt_returntransfer, 1);     $output = curl_exec ($ch);     echo $output;    Curl_close ($ch);      ? >

The results of the browser operation are:

Name=lei&msg=are you OK?

Here we construct an array to be passed to the server as post data:

    • curl_setopt($ch, CURLOPT_POST, 1)indicates a POST request;

    • curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60)Set a longest tolerable connection time, seconds, can not always wait to become a mummy it;

    • curl_setopt($ch, CURLOPT_POSTFIELDS , http_build_query($data))Set the data field of the post, because this is the array data form (and so on JSON format), so use to deal with it http_build_query .

For JSON data , how do you make a POST request?

<?php     $data = ' {' name ': ' Lei ', ' msg ': ' Is you OK? '};    $ch = Curl_init ();     curl_setopt ($ch, Curlopt_url, "http://test server IP mosaic/testrespond.php");     curl_setopt ($ch, Curlopt_post, 1);    curl_setopt ($ch, Curlopt_connecttimeout,);     curl_setopt ($ch, Curlopt_httpheader, Array (' Content-type:application/json ', ' content-length: '. strlen ($data)));    curl_setopt ($ch, Curlopt_postfields, $data);    curl_setopt ($ch, Curlopt_returntransfer, 1);     $output = curl_exec ($ch);     echo $output;    Curl_close ($ch);      ? >

Browser execution, display:

{"Name": "Lei", "MSG": "is OK?"}

3. How to upload and download files

Already and the server hooked up, this time need a photo to look at it, you also have to send their photos to let people look at, although two people in the appearance is not important, but the man June is always the best girl.

3.1 Pass a picture of yourself past table--post upload file

The same remote server side we first send a receive script, receive pictures and save to local, attention to file and folder permissions issues, need to have write permission:

<?php    if ($_files) {        $filename = $_files[' upload ' [' name '];          $tmpname = $_files[' upload ' [' tmp_name '];          Save the picture to the directory where the current script          is located if (Move_uploaded_file ($tmpname, DirName (__file__). /'. $filename)} {            echo (' upload successful ');          }    }? >

Then we'll write the parts of our local server php curl :

<?php     $data = Array (' name ' = ' boy ', ' upload ' = ' @boy. png ');    $ch = Curl_init ();     curl_setopt ($ch, Curlopt_url, "http://remote server address mosaic/testrespond.php");     curl_setopt ($ch, Curlopt_post, 1);    curl_setopt ($ch, Curlopt_connecttimeout,);     curl_setopt ($ch, Curlopt_postfields, $data);    curl_setopt ($ch, Curlopt_returntransfer, 1);     $output = curl_exec ($ch);     echo $output;    Curl_close ($ch);         ? >

Browser run a bit, what all meters have, to see a remote server, or nothing, and did not upload successfully.

why is that? The above code should be people search the curl php POST图片 most common code, this is because I now use the PHP5.6 above version, the @ symbol PHP5.6 after the discard, PHP5.3 still can use, so some students found to execute AH, some found can not be executed, Probably because the PHP version is different, and curl in these two versions of the implementation is incompatible, above is PHP5.3 the implementation.

Here are the PHP5.6 and later implementations:

<?php     $data = Array (' name ' = ' boy ', ' upload ' and ' = ');    $ch = Curl_init ();     $data [' Upload ']=new curlfile (Realpath (GETCWD (). /boy.png '));    curl_setopt ($ch, Curlopt_url, "http://115.29.247.189/test/testRespond.php");    curl_setopt ($ch, Curlopt_post, 1);    curl_setopt ($ch, Curlopt_connecttimeout,);     curl_setopt ($ch, Curlopt_postfields, $data);    curl_setopt ($ch, Curlopt_returntransfer, 1);     $output = curl_exec ($ch);     echo $output;    Curl_close ($ch);         ? >

This introduces an CURLFile object for implementation, which is understood in detail in this document. Then go to the remote server directory to see, found that there is a picture, and indeed we just uploaded the picture.

3.2 Getting a remote server sister's photos--grab pictures

Server sister is also quite honest, looked at according to cheat think I grow quite motherly, on the generous to take out her own photos, but a little shy is, she does not want to take the initiative, we have to take.

The remote server stored a picture in her own directory girl.jpg , the address is 她的web服务器根目录/girl.jpg , and now I'm going to get this picture.

<?php     $ch = Curl_init ();     $fp =fopen ('./girl.jpg ', ' W ');    curl_setopt ($ch, Curlopt_url, "http://remote server address mosaic/girl.jpg");     curl_setopt ($ch, Curlopt_connecttimeout,);     curl_setopt ($ch, Curlopt_file, $fp);     $output = curl_exec ($ch);     $info = Curl_getinfo ($ch);    Fclose ($FP);    $size = FileSize ("./girl.jpg");    if ($size! = $info [' size_download '] {        echo "downloaded data is incomplete, please re-download";    } else {        echo "Download data complete";    }    Curl_close ($ch);    ? >

Now, in our current directory, there is a picture just got, is not very excited!

Here is worth talking about is the curl_getinfo method, this is a method to obtain information about this request, for debugging is very helpful, to use.

4. HTTP Authentication how to do

This time, the server's parents said this our daughter is too small, can not find the object, will her daughter closed up, and on a password lock, the so-called HTTP authentication, the server secretly carrier Pigeon will be HTTP Authentication user name and password to you, to see her, take her to elope.

Then get the user name and password, how can we PHP CURL fix HTTP authentication?

PS: Here lazy don't go to take HTTP authentication to try, directly put a piece of code, we analyze under.

function Curl_auth ($url, $user, $passwd) {    $ch = Curl_init ();    Curl_setopt_array ($ch, [        curlopt_userpwd = $user. ': '. $passwd,        curlopt_url     = $url,        curlopt_ Returntransfer = True    ]);    $result = curl_exec ($ch);    Curl_close ($ch);    return $result;} $authurl = '/http ' to request HTTP authentication address '; Echo curl_auth ($authurl, ' vace ', ' passwd ');

Here is a place to compare the meaning:
curl_setopt_arrayThis method can be used to set multiple parameters one at a time, preventing some dense methods that require multiple settings curl_setopt .

5. Using cookies to simulate landing

At this time you successfully met the server sister, want to take her to elope, but helpless no travelling expenses go far, server sister said, her mother on the server has a treasury, can land to do a little down.

First of all, let us analyze, this thing in two steps, one is to login interface through the account password login, and then get the cookie, the second is to use the cookie simulation landing to the information page to obtain information, the approximate framework is such.

<?php   //Set post data    $post = array (     ' email ' + ' account ',     ' pwd ' = ' password '  );   Login address    $url = "Login Address";    Set cookie save path    $cookie = DirName (__file__). '/cookie.txt ';    The address to obtain information after logging in    $url 2 = "Address of the user to obtain information after landing";    Analog login   login_post ($url, $cookie, $post);    Get information about the login page    $content = get_content ($url 2, $cookie);    Delete cookie file   @ unlink ($cookie);       Var_dump ($content);    ? >

Then we think about the following two ways to implement:

    • login_post($url, $cookie, $post)

    • get_content($url2, $cookie)

Analog login  function login_post ($url, $cookie, $post) {     $curl = Curl_init ();    curl_setopt ($curl, Curlopt_url, $url);    curl_setopt ($curl, Curlopt_returntransfer, 0);    curl_setopt ($curl, Curlopt_cookiejar, $cookie);    curl_setopt ($curl, Curlopt_post, 1);    curl_setopt ($curl, Curlopt_postfields, Http_build_query ($post));    Curl_exec ($curl);     Curl_close ($curl);}
After successful login, get data  function get_content ($url, $cookie) {     $ch = Curl_init ();     curl_setopt ($ch, Curlopt_url, $url);     curl_setopt ($ch, Curlopt_header, 0);     curl_setopt ($ch, Curlopt_returntransfer, 1);     curl_setopt ($ch, Curlopt_cookiefile, $cookie);     $rs = curl_exec ($ch);     Curl_close ($ch);     return $rs; }

At this point, finally, the success of the simulation landing, all smooth, through php CURL the "sultry" server is so simple.

Of course, CURL the ability to do more than this, this article only want to the back-end PHP development of the most commonly used in several scenarios to do a collation and induction. The last sentence, specific problems specific analysis.

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.