In php, you can use curl to simulate http requests and obtain the http response header and body. Of course, you can also set parameters to retrieve only one of them. When both the response header and body are obtained, they are returned as results. We need to separate them by ourselves.
The following code simulates an http GET request to google
| The code is as follows: |
Copy code |
Function httpGet (){ $ Url = 'http: // www.google.com.hk '; $ Ch = curl_init (); Curl_setopt ($ ch, CURLOPT_URL, $ url ); Curl_setopt ($ ch, CURLOPT_HEADER, TRUE); // indicates the response header Curl_setopt ($ ch, CURLOPT_NOBODY, FALSE); // response body Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, TRUE ); Curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, FALSE ); Curl_setopt ($ ch, CURLOPT_AUTOREFERER, TRUE ); Curl_setopt ($ ch, CURLOPT_TIMEOUT, 120 ); $ Result = curl_exec ($ ch ); If (curl_getinfo ($ ch, CURLINFO_HTTP_CODE) = '20140901 '){ Return $ result; } Return NULL; } |
After calling the above method, the output is similar to the following:
HTTP/1.1 200 OK
Date: Tue, 09 Jul 2013 14:21:08 GMT
Expires:-1
Cache-Control: private, max-age = 0
Content-Type: text/html; charset = UTF-8
Set-Cookie: PREF = ID = 75e996a7ad21f47b: FF = 0: NW = 1: TM = 1373379668: LM = 1373379668: S = TTLQQN-rjgdyky; expires = Thu, 09-Jul-2015 14:21:08 GMT; path =/; domain = .google.com.hk
Set-Cookie: NID = 67 = PPu7FfFeuZqwfsrUifgzjidX4JZxxCPLe9xFHjdXhfHpzs3gaykFSH5uGXy2esWTlp_rdqIYkjFDMollzI_sA-8owxD3mDh6KCRwdMa9-g5VChj0E5XAGNjo9d-sZfLN; expires = Wed, 08-Jan-2014 14:21:08 GMT; path =/; domain = .google.com.hk; HttpOnly
P3P: CP = "This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py? Hl = en & answer = 151657 for more info ."
Server: gws
X-XSS-Protection: 1; mode = block
X-Frame-Options: SAMEORIGIN
Transfer-Encoding: chunked
<! Doctype html> Window. google = {kEI: "vbzcudwuhomti1_64ihocw", getEI: function (a) {for (var B; &&(! A. getAttribute |! (B = a. getAttribute ("eid ")));
......
Here we can see that the header and body information are in the same result. How can we separate them. There are two methods. One is to get the length of the header through the curl_getinfo () method that comes with curl, and then use substr to split the string. The sample code is as follows:
| The code is as follows: |
Copy code |
$ Response = curl_exec ($ ch ); If (curl_getinfo ($ ch, CURLINFO_HTTP_CODE) = '20140901 '){ $ HeaderSize = curl_getinfo ($ ch, CURLINFO_HEADER_SIZE ); $ Header = substr ($ response, 0, $ headerSize ); $ Body = substr ($ response, $ headerSize ); } |
The second method is based on the header and body separated by two carriage return line breaks, so the following code can be used:
| The code is as follows: |
Copy code |
$ Response = curl_exec ($ ch ); If (curl_getinfo ($ ch, CURLINFO_HTTP_CODE) = '20140901 '){ List ($ header, $ body) = explode ("rnrn", response, 2 ); } |