PHP Use Curl Detailed analysis and problem summary _php tips

Source: Internet
Author: User
Tags curl curl options http authentication http post json ssl certificate

Tanabata, as the development, the sister did not "up" on the server it, girls have a hot classmate that left hug sister right hold server it, and sister is to gift, the server does not need. Well, long story short again, sacrifice today's tool--curl (Client URL Library), of course, today in PHP's way to use this tool.

0. Curl is a thing.

Copy Code code as follows:
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, simply put, curl is a library that allows you to hook up, chat and communicate with many different kinds of servers, and support many protocols. And others said curl can support HTTPS authentication, HTTP POST, FTP upload, agent, cookies, simple password authentication and so on.

Say so many actually have no feeling, have a feeling in the application only, I also need to start a POST request on server side to another server to begin to contact Curl, then have a feeling.

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

1. Try Taker first.

Tools to hand, first to play, try to shun smoothly, or a take to use, your own code to make a foul smoke how to get to the server?

For example, we take the famous "test network is connected" website--Baidu as an example, to try the next 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 
  curl_close ($ch);   
? >

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

The code and comments above have fully explained what the 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 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 the setting whether the response result is stored in a variable, 1 is deposited, and 0 is directly echo out;

$output = curl_exec($ch)Execute, and then deposit the result of the response into the $output variable for echo below;

Curl_close ($ch) Closes this Curl session resource.

PHP in the use of curl is roughly such a form, where the second step, through the Curl_setopt method to set parameters is the most complex and most important, interested can go to see the official information on the parameters can be set for detailed reference, long to let you see to vomit, or according to practice practice it.

To summarize, the Curl usage in PHP is to create Curl session-> configuration Parameters-> Execute-> shutdown session.

Let's take a look at some common scenarios where we need to "dress ourselves" (Configure the parameters) to be properly "sexy" (to the server correctly).

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

First and the server to say hello to the server to send a hello to see how she returned, here the most convenient way is to send a GET request to the server, of course, post this small note also ok slightly.

2.1 GET Request

For example, we use "search keywords in a famous gay dating website GitHub"

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 
  curl_close ($ch);   
? >

It seems to be no different from the previous example, but here are 2 points to mention:

1. The default request method is get, so you do not need to explicitly specify a GET method;
2.https requests, non-HTTP requests, there may be people in various places have seen the HTTPS request requires several lines of code to bypass the SSL certificate, and other ways to successfully request resources, but here does not seem to need, what is the reason?

Copy Code code as follows:
The two Curl options are defined as:

Curlopt_ssl_verifypeer-verify The peer ' s SSL certificate
Curlopt_ssl_verifyhost-verify the certificate ' s name against host
They both default to True in Curl, and shouldn ' t is disabled unless you ' ve got a good reason. Disabling them is generally only needed if ' re sending requests to servers with invalid or self-signed certificates, WH The ICH is only usually a issue in development. Any publicly-facing site should is presenting a valid certificate, and by disabling this options you ' re potentially openi Ng yourself up to the security issues.

That is, unless you use an illegal or homemade certificate, most of which appear in the development environment, you are setting these two lines to false to avoid SSL certificate checking, which is not a safe way to do this.

2.2 POST Request

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

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" => "Are 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, while trying to connect. Use 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 run 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 one the longest tolerable connection time, the second unit, the total can not always wait to become a mummy bar;
curl_setopt ($ch, Curlopt_postfields, Http_build_query ($data)) Sets the data field for the post, because it is in the form of array data (and so on JSON format), so use Http_build_ Query to handle it.

What about JSON data, and how do I post a request?

<?php 
  $data = ' {' name ': ' Lei ', ' msg ': ' Are 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, showing:

{"Name": "Lei", "MSG": "Are you OK?"}

3. How to upload and download files

has been hooked up with the server, this time to take a picture to see it, you have to send their own photos to let people see, although two of people together appearance is not important, but the handsome men are always the best.

3.1 Send a picture of yourself past the table in good faith--post upload file

The same remote server side we first pass 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 current script's directory
     if (Move_uploaded_file ($tmpname, DirName (__file__). ' /'. $filename)) {
      echo (' upload succeeded ');
     }
? >

And then we'll write the Php curl part of our local server:

<?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 to run a bit, what are rice, to see a remote server, or nothing, and did not upload success.

Why is that? The code above should be the most common code for everyone searching for curl PHP post pictures, because I'm using the PHP5.6 version, @ The symbol in the PHP5.6 after the discard, PHP5.3 still can use, so some students found that can perform Ah, some found not to execute, probably because of the different versions of PHP, and curl in the two versions of the implementation is incompatible, above is the realization of the PHP5.3.

Here are the PHP5.6 and future implementations:

<?php 
  $data = Array (' name ' => ' Boy ', ' upload ' => ");
  $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);     
? >

A Curlfile object is introduced here to understand the specific documentation available for this. Then go to the remote server directory to see, found that there is a picture, and indeed we have just uploaded the picture.

3.2 Get remote server photos of sister--grab pictures

Server sister is also very honest, looked at the cheat think I am very motherly, generous to take out her own photos, but a bit shy is, she is not willing to take the initiative, we have to fetch.

The remote server has a picture called girl.jpg in her own directory, the address is her Web server root directory/girl.jpg, and now I'm going to get this photo.

<?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 is not fully downloaded, please download again;}
  else {
    echo "Download data complete";
  }

  Curl_close ($ch);  
? >

Now, in our current directory there is a just get the photo, is not very excited about it!

Here is worth saying is the Curl_getinfo method, this is a obtain this request related information method, is helpful to the debugging, should use.

4. HTTP authentication how to engage

At this time, the parents of the server said that our daughter was too young, can't find the object, will her daughter shut up, and on a password lock, the so-called HTTP authentication, the server is secretly carrier Pigeon will be HTTP authenticated username and password to you, want you to see her, take her elope.

So with the username and password, how do we get the HTTP authentication through PHP curl?

PS: Here lazy will not go to the HTTP authentication to try, put a piece of code directly, we analyze.

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 authenticated address ';

Echo Curl_auth ($authurl, ' vace ', ' passwd ');

Here is a place that is more interesting:
Curl_setopt_array This method can be used to set multiple parameters at once, to prevent some need to set up a number of curl_setopt methods.

5. Use cookies to simulate landing

At this time you successfully saw the server sister, want to take her elopement, but helpless no money go not far, server sister said, her mother server has a vault, you can land to get a little down.

First of all, we analyze this matter in two steps, one is to login interface through the account password login, and then get cookies, the second is to use cookies to simulate landing to information page to get information, the general framework is this.

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

 Var_dump ($content);  
? >

Then we think about the implementation of the following two methods:

Login_post ($url, $cookie, $post)
get_content ($url 2, $cookie)
//Simulate 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);
Get Data 
function get_content ($url, $cookie) { 
  $ch = Curl_init () 
  after successful login 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 is the simulation landing success, everything goes well, through the PHP CURL "hot" server is so simple.

Of course, curl's ability is much more than this, this article only wants to be in the back-end PHP development most commonly used several scenes to do a collation and induction. The last sentence, concrete analysis of specific issues.

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.