PHP sends requests to other servers through curl and returns data

In many cases, we need to request the third-party server to obtain some data, such as token, such as Baidu's active push, so how does our php rea...

In many cases, we need to request the third-party server to obtain some data, such as token, such as Baidu's active push, so how does our php realize the request to the third-party server? We can do this with curl

First define the url of the request, then create the header of the httpHeader, and define the parameters to send the request by post:

Initialize curl:

1 $url="URL address"; 2 3 //Then create httpHeader Head: 4 5 $httpHeader=createHttpHeader(); 6 7 //Definition passed post Send request by: 8 9 $curlPost="userId=".$userId."&name=".$nickName."&portraitUri=".$headImg; 10 11 //Initialization curl: 12 13 $ch=curl_init();undefined

Send request:

1 curl_setopt($ch,CURLOPT_URL,$url); 2 curl_setopt($ch,CURLOPT_HTTPHEADER,$httpHeader); 3 curl_setopt($ch,CURLOPT_HEADER,false); 4 curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); 5 curl_setopt($ch,CURLOPT_POST,1); 6 curl_setopt($ch,CURLOPT_POSTFIELDS,$curlPost); 7 curl_setopt($ch,CURLOPT_TIMEOUT,30); 8 curl_setopt($ch,CURLOPT_DNS_USE_GLOBAL_CACHE,false); 9 curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);undefined

Receive the returned data: $data=curl_exec($ch); close curl: curl_close($ch); this completes a post request through curl and obtains the returned data.

complete PHP source code As follows:

1 $url="Requested URL address"; 2 $httpHeader=createHttpHeader(); 3 $curlPost="userId=".$userId."&name=".$nickName."&portraitUri=".$headImg; 4 $ch=curl_init(); 5 curl_setopt($ch,CURLOPT_URL,$url); 6 curl_setopt($ch,CURLOPT_HTTPHEADER,$httpHeader); 7 curl_setopt($ch,CURLOPT_HEADER,false); 8 curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); 9 curl_setopt($ch,CURLOPT_POST,1); 10 curl_setopt($ch,CURLOPT_POSTFIELDS,$curlPost); 11 curl_setopt($ch,CURLOPT_TIMEOUT,30); 12 curl_setopt($ch,CURLOPT_DNS_USE_GLOBAL_CACHE,false); 13 curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); 14 $data=curl_exec($ch); 15 curl_close($ch);undefined

2 December 2019, 14:52 | Views: 6281

Add new comment

For adding a comment, please log in
or create account

0 comments