Detailed analysis and problem summary of php curl

Source: Internet
Author: User
Tags curl options
CURL is a very powerful open-source library that supports many protocols, including HTTP, FTP, and TELNET. We use it to send HTTP requests. It brings us the benefit of setting different HTTP parameters through flexible options and supporting HTTPS. CURL automatically selects whether to encrypt the sent content based on whether the URL prefix is "HTTP" or "HTTPS. Take advantage of today's tool-CURL (Client URL Library). of course, this tool is used in PHP today.

0. what is curl?

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.

This is a PHP explanation of curl. Simply put, curl is a library that allows you to hook up, chat, and communicate with many different types of servers through URLs, it also supports many protocols. They also said that curl can support https authentication, http post, ftp upload, proxy, cookies, simple password authentication, and other features.

After talking about this, there is actually no sense. in the application, I felt that at first I had to initiate a POST request to another server on the server side before I began to access curl, then you will feel it.

Before officially speaking about how to use the curl module, you must install and enable the curl module in your PHP environment, you can check it on google or consult the official PHP documentation, which is quite simple.

1. try it first.

To get the tool, you must first try it. Otherwise, you can use it as soon as you get it. how can you get your own code to hack the server?

For example, we use Baidu, the famous website "test whether the network is connected", to try curl

 

When you open the php file in the local environment browser, the page displays the Baidu homepage. what about the "localhost" I just entered?

The above code and comments fully demonstrate what the code is doing.

$ Ch = curl_init (): Creates a curl Session resource and returns a handle;
Curl_setopt ($ ch, CURLOPT_URL, "baidu.com"), set the URL, needless to say;

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

Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 0) is used to set whether to save the response result to a variable, 1 is saved, and 0 is directly echo;

$ Output = curl_exec ($ ch) execution, and then save the response result to the $ output variable for the following echo;

Curl_close ($ ch) closes the curl Session resource.

The use of curl in PHP is roughly in this form. in step 2, setting parameters through the curl_setopt method is the most complex and important, if you are interested, you can refer to the official detailed reference on configurable parameters to make you think about it for a long time.

In php, the curl usage is: Create a curl session-> configure parameters-> Execute-> Close a session.

Next, let's look at some common scenarios. we need to "dress up ourselves" (configure parameters) to correct "Xiaomei" (correctly forwarded to the server ).

2. say hello-GET and POST requests and HTTPS protocol processing

First, say Hello to the server and send a Hello to the server to see how she returned. the most convenient way here is to send a GET request to the server. of course, it is okay to POST a small piece of paper.

2.1 GET request

Let's take "search for keywords in a famous dating site github" as an example.

// Use curl for GET requests
 

It seems that there is no difference with the previous example, but there are two points to mention:

1. the default request method is GET, so you do not need to explicitly specify the GET method;
2. https requests, non-http requests. some people may have seen HTTPS requests in various places. they need to add several lines of code to bypass the SSL certificate check and other methods to successfully request resources. However, this does not seem necessary, why?

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 hostThey both default to true in Curl, and shouldn't be disabled unless you've got a good reason. Disabling them is generally only needed if you're sending requests to servers with invalid or self-signed certificates, which is only usually an issue in development. Any publicly-facing site should be presenting a valid certificate, and by disabling these options you're potentially opening yourself up to security issues.

That is, unless an invalid or self-made certificate is used, most of the certificates appear in the development environment. you can set these two lines to false to avoid ssl certificate check. Otherwise, you do not need to do this, this is unsafe.

2.2 POST request

So how to make a POST request? For testing, a script for receiving POST is first transmitted on a test server:

//testRespond.php
 

Send common data

Then write a request locally:

 "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 wait while trying to connect. use 0 to wait indefinitely. curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt ($ ch, CURLOPT_POSTFIELDS, http_build_query ($ data); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 ); $ output = curl_exec ($ ch); echo $ o Utput; curl_close ($ ch);?>

The browser running result is:

Name = Lei & msg = Are you OK?

Here we construct an array to send POST data to the server:

Curl_setopt ($ ch, CURLOPT_POST, 1) indicates a POST request;
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, 60) sets the longest tolerable connection time, in seconds. you cannot wait until it becomes a mummy;
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, http_build_query ($ data) is used to set the POST data field. because it is in the form of array data (such as json format), use http_build_query to process it.

How can I make a POST request for json data?

 

Execute in the browser and display:

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

3. how to upload and download files

I have already hooked up with the server. at this time, I have to take a photo to see it. you have to send your own photo so that you can see it. although the appearance of two people together is not important, however, handsome men and girls are always the best.

3.1 upload a picture of yourself in the past, table sincerity-POST Upload files

Similarly, on the remote server, we first upload a receiving script to receive images and save them to the local device. pay attention to the file and folder permissions and require the write permission:

 

Then we will write the php curl section of our local server:

 'Boys', "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, 60); curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ data); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); $ output = curl_exec ($ ch); echo $ output; curl_close ($ ch);?>

Run the script in the browser. everything is in meters. check whether the remote server is running or not, and the upload is successful.

Why? The above code should be the most common code for searching curl php POST images. this is because I am using PHP5.6 or later, and the @ symbol is discarded after PHP5.6, PHP5.3 can still be used, so some people find that PHP can be executed. some of them cannot be executed, because PHP versions are different, and curl is not compatible in these two versions, the above is the implementation of PHP5.3.

PHP5.6 and later implementation ,:

 '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, 60);   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 for implementation. for details about this, refer to the documentation. At this time, go to the remote server directory and check that there is an image, and it is indeed the image we just uploaded.

3.2 get photos of remote server sisters-capture images

The server sister is also very honest. after seeing the picture, I think that I am very kind, I have to show her own photos, but I am a little shy that she is not willing to take it, we have to retrieve it by ourselves.

The remote server stores the image girl.jpg in her Directory. The address is the root directory of her web server/girl.jpg. now I want to get this picture.

 

Now, we have a new photo in our current directory. are you very excited!

It is worth mentioning that the curl_getinfo method is a method to obtain information about this request. it is very helpful for debugging and should be used properly.

4. how to implement HTTP authentication

At this time, the parent of the server said that our daughter was too small to find an object, so she shut down her daughter and got a password lock, the so-called HTTP authentication, the server secretly gave you the HTTP authentication username and password, asking you to see her and take her away.

So how can we get HTTP authentication through php curl with the user name and password?

PS: If you are lazy, you will not try HTTP authentication. put a piece of code directly. let's analyze it.

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: // address to request http authentication '; echo curl_auth ($ authurl, 'vace', 'passwd ');
Here is an interesting place: the curl_setopt_array method can be used to set multiple parameters at a time through arrays to prevent some curl_setopt methods that require multiple settings. 5. when using cookies to simulate login, you successfully saw the server sister and wanted to take her away, but she had no chance to leave it. the server sister said that there was a vault on her mother's server, you can log on to the system and try again. First, let's take a look at this process. The first step is to log on to the logon page using the account and password, and then obtain the cookie. The second step is to use the cookie to simulate login to the information page to obtain information, the general framework is like this.
 'Account', 'pwd' => 'password'); // logon address $ url = "logon address "; // Set the cookie storage path $ cookie = dirname (_ FILE __). '/cookie.txt'; // address for obtaining information after login $ url2 = "address for obtaining information after login"; // simulate login_post login ($ url, $ cookie, $ post); // Get the login page information $ content = get_content ($ url2, $ cookie); // delete the cookie file @ unlink ($ cookie ); var_dump ($ content);?>

Then let's think about the implementation of the following two methods:

Login_post ($ url, $ cookie, $ post) get_content ($ url2, $ cookie) // simulate login function login_post ($ url, $ cookie, $ post) {$ curl = curl_init (); curl_setopt ($ curl, CURLOPT_URL, $ url); curl_setopt ($ curl, expires, 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 );} // function get_content ($ url, $ cookie) {$ ch = curl_init (); curl_setopt ($ ch, CURLOPT_URL, $ url); curl_setopt ($ ch, $ 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, the login was successfully simulated, and everything went well. it was so simple to use the php CURL "login" server.

Of course, CURL is far more powerful than that. This article only wants to organize and summarize the most common backend PHP development scenarios. The last sentence is a detailed analysis of the problem.

For more articles about using curl in php and problem summary, refer to PHP!

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.