The content of this article is about PHP sending requests to other servers and returning data (code examples) through curl. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
In many cases, we need to request a third-party server to obtain some data, such as tokens, such as Baidu's active push. So how does our PHP make requests to the third-party server? We can achieve this through curl
First define the requested url, then create the httpHeader header, and define the parameters for sending the request through post:
Initialize curl:
$url="URL地址"; //然后创建httpHeader的头: $httpHeader=createHttpHeader(); //定义通过post方式发送请求的参数: $curlPost="userId=".$userId."&name=".$nickName."&portraitUri=".$headImg; //初始化curl: $ch=curl_init();undefined
Send request:
curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_HTTPHEADER,$httpHeader); curl_setopt($ch,CURLOPT_HEADER,false); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$curlPost); curl_setopt($ch,CURLOPT_TIMEOUT,30); curl_setopt($ch,CURLOPT_DNS_USE_GLOBAL_CACHE,false); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);undefined
Receive the returned data: $data=curl_exec($ ch); Close curl: curl_close($ch); In this way, a post request is completed through curl and the returned data is obtained.
The complete PHP source code is as follows:
$url="请求的URL地址"; $httpHeader=createHttpHeader(); $curlPost="userId=".$userId."&name=".$nickName."&portraitUri=".$headImg; $ch=curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_HTTPHEADER,$httpHeader); curl_setopt($ch,CURLOPT_HEADER,false); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$curlPost); curl_setopt($ch,CURLOPT_TIMEOUT,30); curl_setopt($ch,CURLOPT_DNS_USE_GLOBAL_CACHE,false); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); $data=curl_exec($ch); curl_close($ch);undefined
The above is the detailed content of PHP sends requests to other servers through curl and returns data (code example). For more information, please follow other related articles on the PHP Chinese website!