本文作者:DurkBlue

PHP 使用 curl 发送请求拉取接口数据(最全面)以及返回 false的相关处理及其错误代码代表含义推荐

DurkBlue 2023-11-15 32308
PHP 使用 curl 发送请求拉取接口数据(最全面)以及返回 false的相关处理及其错误代码代表含义摘要: 博主总结了一下迄今未知开发至今的有关于curl用的的所有设置,集成到了这个方法当中,其他程序员可以把它当作一个公共函数或者一个公共类的公共方法调用即可(需根据自己的业务调整代码),...


博主总结了一下迄今未知开发至今的有关于curl用的的所有设置,集成到了这个方法当中,其他程序员可以把它

当作一个公共函数或者一个公共类的公共方法调用即可(需根据自己的业务调整代码),其代码如下:


/**
* @Notes: curl发起远程会话
* @Author:DurkBlue
* @Time: 2024/3/29 9:25
* @param string $url 请求的URL
* @param string $method 请求方式
* @param array $data 请求数据
* @param array $header 请求头
* $headers = array(
   "Content-Type: application/json",
   "Content-Length: " . strlen($jsonStr) . "",
   "Accept: application/json",
   "client-id:DurkBlue",    //自定义参数
   "client-secret:DurkBlueSecret"  //自定义参数
   );
* @param bool $needHttpSSL 发起的请求是否需要认证HttpSSL证书
* @return bool|string 为false代表请求失败,为string表示请求成功,返回响应数据
* @Interface http_request
*/
private static function http_request(string $url, string $method = 'POST', array|string $data = [],  array $header = [], bool $needHttpSSL = false):bool|string{

   $curl = curl_init(); // 启动一个CURL会话
   curl_setopt($curl,CURLOPT_URL,$url); // 要访问的地址
   curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);// 不检查证书来源
   curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 不从证书检查SSL加密算法是否存在
   curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
   curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);//重定向后继续访问location中的内容
   curl_setopt($curl, CURLOPT_AUTOREFERER, 1);// 自动设置Referer
   //这里设置代理,如果有的话
   //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
   //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
   if($needHttpSSL) {
       curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
       curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
       curl_setopt($curl, CURLOPT_SSLVERSION, 4); // 设置SSL证书版本
       //设置证书
       //使用证书:cert 与 key 分别属于两个.pem文件
       //默认格式为PEM,可以注释
       curl_setopt($curl,CURLOPT_SSLCERTTYPE,'PEM');// 检查的证书类型
       curl_setopt($curl,CURLOPT_SSLCERT,'/data/cert/php.pem'); // 检查的证书签名路径这是cert文件路径
       curl_setopt($curl,CURLOPT_SSLCERTPASSWD,'1234'); // 递交证书密码有就设置没有就删除这行代码
       //默认格式为PEM,可以注释
       curl_setopt($curl,CURLOPT_SSLKEYTYPE,'PEM'); // 检查证书类型
       curl_setopt($curl,CURLOPT_SSLKEY,'/data/cert/php_private.pem'); // 检查的证书key文件路径
   }
   if(!empty($header)) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);// 设置header请求头数据
   if($method=='POST'){
       curl_setopt($curl, CURLOPT_POST, 1);// 发送一个常规的Post请求
       if(!empty($data)) curl_setopt($curl, CURLOPT_POSTFIELDS, $data);// Post提交的数据包
   }else if($method=='GET'){
       if(!empty($data)){
           if(is_array($data)) $url = $url.'?'.http_build_query($data); // 将请求数组转化成url请求参数字符串
           else{
               $data = json_decode($data, true);
               $url = $url.'?'.http_build_query($data);
           }
       }
   }
   curl_setopt($curl, CURLOPT_TIMEOUT, 30);// 设置超时限制防止死循环
   curl_setopt($curl, CURLOPT_HEADER, 0);// 显示返回的Header区域内容
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 获取的信息以文件流的形式返回
   $result = curl_exec($curl); // 执行操作
   if (curl_errno($curl)){
       //var_dump(curl_error($curl));
       return false;
   }
   curl_close($curl);// 关闭CURL会话
   return $result;// 返回数据
}


PHP 使用 curl 发送请求拉取接口数据(最全面)以及返回 false的相关处理及其错误代码代表含义  第1张


调用代码:


//获取省级地区
    public function getAddressProvinceData(){
        $token = $this->getAccessToken();
        if($token == 'fail') return 'fail';
        //请求参数
        $request_data = [
            'access_token'  => $token,
            'code'          => 0
        ];
        $url = $this->apiurl . '/api/regions/get_region_code';
        $response = $this->http_request($url,json_encode($request_data));
        $result = json_decode($response,true);
        if($result['error_code'] == 0){
            exit;
            $result_data = $result['result'];
            $val = $result_data[34];
            $insert['name'] = $val['name'];
            $insert['code'] = $val['code'];
            $insert['parent_code'] = 0;
            $insert['available'] = json_encode($val['available']);
            pdo_insert('ewei_weiweibao_address',$insert);
            $this->getAddressCityData($val['code']);
            echo 'SUCCESS';exit;
            foreach ($result_data as $val) {
                $insert['name'] = $val['name'];
                $insert['code'] = $val['code'];
                $insert['parent_code'] = 0;
                $insert['available'] = json_encode($val['available']);
                pdo_insert('ewei_weiweibao_address',$insert);
                $this->getAddressCityData($val['code']);
            }
        }
    }



附注:PHP 使用 curl 返回 false 的情况处理


一般情况下使用 php curl 去模拟访问 http 或者 https 可能会出现一些莫名其妙的问题,让人不好查找错误。

比如,以下是伪代码:


$response = curl_exec($ch);
return $response;



在执行后 curl 操作后发现返回:


bool(false)



像这样的错误,是比较懵逼的。

这时可以使用 curl_error 返回错误信息进行查找,比如以下代码:


$response = curl_exec($ch);
$error = curl_error($ch)
var_dump($error);exit(0);
return $response;



记住执行 curl_error 一定要在 curl_exec 函数后,否则大概率返回以下内容:


string(0) ""



显然,这对于找出错误毫无意义。正常输出错误如下:


string(26) "Port number ended with '\'"



接下来就根据错误信息开始排除出错原因。


但是 ,有些情况下,依然可能会返回空字符串,无法打印出真正的错误。这时,可以通过 curl_errno 返回错误编码,查找相应编码的错误,再把问题给解决。


记住执行 curl_errno 一定也要在 curl_exec 函数后,否则大概率返回以下内容:


int(0)



寻找错误编码代码如下:


$response = curl_exec($ch);
//$error = curl_error($ch)
//var_dump($error);exit(0);
$errno = curl_errno($ch)
var_dump($errno);exit(0);
return $response;



错误输出如下:

int(3)


之后根据错误代码进行排错纠察即可。


常见返回 fasle 处理方案,要根据你的实际情况进行调整,这里只是为了测试,放开所有权限:


curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    //信任任何证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);        //表示不检查证书


顺便记录一下,如果错误代码是 77 ,则需要重启 Apache 即可。



PHP cURL curl_errno

在php程序编写中,使用curl函数库的几率还是挺高的,如curl_init()、curl_setopt()、curl_exec()、curl_errno()等都是常用的函数,尤其是在获取网页相关信息的时候。
在使用这些函数的时候,有时会遇到一些问题,如之前遇到的IIS运行PHP出现Call to undefined function curl_init()的问题,这些问题一般都比较基础,遇到问题并解决问题,是一个程序员成长的历程,在解决问题的过程中能学会更多问题之外的知识。
今天在使用curl_errno()时,新的问题又出现了。如下语句:
if(!curl_errno($url)){... ...}
程序运行时,{... ...}没有执行,说明if(!curl_errno($url))条件不为真。不过是仅仅知道了条件不为真这个结果,而不知道为什么不为真,哪里出的问题?所以,这个问题需要进一步诊断,那就是从curl_errno($url)的返回值获得错误的信息。
如何从curl_errno返回值获取错误信息
curl_errno($url)会返回一个数值,这个数值可能是0,也可能是其他。当这个数值为0时,则说明没有问题,相当于返回false,而用在条件语句里if(!curl_errno($url)){... ...},加了!后就变为true。所以当返回数值是0时就执行if后面的主体语句,返回其他数值时,不执行if后面的主体语句。
因此,我们需要一个错误号和错误信息的对照表即可,根据错误号找出对应的错误信息。


下面附上错误号及错误信息的对照资料

CURLE_OK (0)
All fine. Proceed as usual.

CURLE_UNSUPPORTED_PROTOCOL (1)
The URL you passed to libcurl used a protocol that this libcurl does not support. The support might be a compile-time option that you didn't use, it can be a misspelled protocol string or just a protocol libcurl has no code for.

CURLE_FAILED_INIT (2)
Very early initialization code failed. This is likely to be an internal error or problem, or a resource problem where something fundamental couldn't get done at init time.

CURLE_URL_MALFORMAT (3)
The URL was not properly formatted.

CURLE_NOT_BUILT_IN (4)
A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. This means that a feature or option was not enabled or explicitly disabled when libcurl was built and in order to get it to function you have to get a rebuilt libcurl.

CURLE_COULDNT_RESOLVE_PROXY (5)
Couldn't resolve proxy. The given proxy host could not be resolved.

CURLE_COULDNT_RESOLVE_HOST (6)
Couldn't resolve host. The given remote host was not resolved.

CURLE_COULDNT_CONNECT (7)
Failed to connect() to host or proxy.

CURLE_FTP_WEIRD_SERVER_REPLY (8)
After connecting to a FTP server, libcurl expects to get a certain reply back. This error code implies that it got a strange or bad reply. The given remote server is probably not an OK FTP server.

CURLE_REMOTE_ACCESS_DENIED (9)
We were denied access to the resource given in the URL. For FTP, this occurs while trying to change to the remote directory.

CURLE_FTP_ACCEPT_FAILED (10)
While waiting for the server to connect back when an active FTP session is used, an error code was sent over the control connection or similar.

CURLE_FTP_WEIRD_PASS_REPLY (11)
After having sent the FTP password to the server, libcurl expects a proper reply. This error code indicates that an unexpected code was returned.

CURLE_FTP_ACCEPT_TIMEOUT (12)
During an active FTP session while waiting for the server to connect, the CURLOPT_ACCEPTTIMOUT_MS (or the internal default) timeout expired.

CURLE_FTP_WEIRD_PASV_REPLY (13)
libcurl failed to get a sensible result back from the server as a response to either a PASV or a EPSV command. The server is flawed.

CURLE_FTP_WEIRD_227_FORMAT (14)
FTP servers return a 227-line as a response to a PASV command. If libcurl fails to parse that line, this return code is passed back.

CURLE_FTP_CANT_GET_HOST (15)
An internal failure to lookup the host used for the new connection.

CURLE_FTP_COULDNT_SET_TYPE (17)
Received an error when trying to set the transfer mode to binary or ASCII.

CURLE_PARTIAL_FILE (18)
A file transfer was shorter or larger than expected. This happens when the server first reports an expected transfer size, and then delivers data that doesn't match the previously given size.

CURLE_FTP_COULDNT_RETR_FILE (19)
This was either a weird reply to a 'RETR' command or a zero byte transfer complete.

CURLE_QUOTE_ERROR (21)
When sending custom "QUOTE" commands to the remote server, one of the commands returned an error code that was 400 or higher (for FTP) or otherwise indicated unsuccessful completion of the command.

CURLE_HTTP_RETURNED_ERROR (22)
This is returned if CURLOPT_FAILONERROR is set TRUE and the HTTP server returns an error code that is >= 400.

CURLE_WRITE_ERROR (23)
An error occurred when writing received data to a local file, or an error was returned to libcurl from a write callback.

CURLE_UPLOAD_FAILED (25)
Failed starting the upload. For FTP, the server typically denied the STOR command. The error buffer usually contains the server's explanation for this.

CURLE_READ_ERROR (26)
There was a problem reading a local file or an error returned by the read callback.

CURLE_OUT_OF_MEMORY (27)
A memory allocation request failed. This is serious badness and things are severely screwed up if this ever occurs.

CURLE_OPERATION_TIMEDOUT (28)
Operation timeout. The specified time-out period was reached according to the conditions.

CURLE_FTP_PORT_FAILED (30)
The FTP PORT command returned error. This mostly happens when you haven't specified a good enough address for libcurl to use. See CURLOPT_FTPPORT.

CURLE_FTP_COULDNT_USE_REST (31)
The FTP REST command returned error. This should never happen if the server is sane.

CURLE_RANGE_ERROR (33)
The server does not support or accept range requests.

CURLE_HTTP_POST_ERROR (34)
This is an odd error that mainly occurs due to internal confusion.

CURLE_SSL_CONNECT_ERROR (35)
A problem occurred somewhere in the SSL/TLS handshake. You really want the error buffer and read the message there as it pinpoints the problem slightly more. Could be certificates (file formats, paths, permissions), passwords, and others.

CURLE_BAD_DOWNLOAD_RESUME (36)
The download could not be resumed because the specified offset was out of the file boundary.

CURLE_FILE_COULDNT_READ_FILE (37)
A file given with FILE:// couldn't be opened. Most likely because the file path doesn't identify an existing file. Did you check file permissions?

CURLE_LDAP_CANNOT_BIND (38)
LDAP cannot bind. LDAP bind operation failed.

CURLE_LDAP_SEARCH_FAILED (39)
LDAP search failed.

CURLE_FUNCTION_NOT_FOUND (41)
Function not found. A required zlib function was not found.

CURLE_ABORTED_BY_CALLBACK (42)
Aborted by callback. A callback returned "abort" to libcurl.

CURLE_BAD_FUNCTION_ARGUMENT (43)
Internal error. A function was called with a bad parameter.

CURLE_INTERFACE_FAILED (45)
Interface error. A specified outgoing interface could not be used. Set which interface to use for outgoing connections' source IP address with CURLOPT_INTERFACE.

CURLE_TOO_MANY_REDIRECTS (47)
Too many redirects. When following redirects, libcurl hit the maximum amount. Set your limit with CURLOPT_MAXREDIRS.

CURLE_UNKNOWN_OPTION (48)
An option passed to libcurl is not recognized/known. Refer to the appropriate documentation. This is most likely a problem in the program that uses libcurl. The error buffer might contain more specific information about which exact option it concerns.

CURLE_TELNET_OPTION_SYNTAX (49)
A telnet option string was Illegally formatted.

CURLE_PEER_FAILED_VERIFICATION (51)
The remote server's SSL certificate or SSH md5 fingerprint was deemed not OK.

CURLE_GOT_NOTHING (52)
Nothing was returned from the server, and under the circumstances, getting nothing is considered an error.

CURLE_SSL_ENGINE_NOTFOUND (53)
The specified crypto engine wasn't found.

CURLE_SSL_ENGINE_SETFAILED (54)
Failed setting the selected SSL crypto engine as default!

CURLE_SEND_ERROR (55)
Failed sending network data.

CURLE_RECV_ERROR (56)
Failure with receiving network data.

CURLE_SSL_CERTPROBLEM (58)
problem with the local client certificate.

CURLE_SSL_CIPHER (59)
Couldn't use specified cipher.

CURLE_SSL_CACERT (60)
Peer certificate cannot be authenticated with known CA certificates.

CURLE_BAD_CONTENT_ENCODING (61)
Unrecognized transfer encoding.

CURLE_LDAP_INVALID_URL (62)
Invalid LDAP URL.

CURLE_FILESIZE_EXCEEDED (63)
Maximum file size exceeded.

CURLE_USE_SSL_FAILED (64)
Requested FTP SSL level failed.

CURLE_SEND_FAIL_REWIND (65)
When doing a send operation curl had to rewind the data to retransmit, but the rewinding operation failed.

CURLE_SSL_ENGINE_INITFAILED (66)
Initiating the SSL Engine failed.

CURLE_LOGIN_DENIED (67)
The remote server denied curl to login (Added in 7.13.1)
CURLE_TFTP_NOTFOUND (68)
File not found on TFTP server.

CURLE_TFTP_PERM (69)
Permission problem on TFTP server.

CURLE_REMOTE_DISK_FULL (70)
Out of disk space on the server.

CURLE_TFTP_ILLEGAL (71)
Illegal TFTP operation.

CURLE_TFTP_UNKNOWNID (72)
Unknown TFTP transfer ID.

CURLE_REMOTE_FILE_EXISTS (73)
File already exists and will not be overwritten.

CURLE_TFTP_NOSUCHUSER (74)
This error should never be returned by a properly functioning TFTP server.

CURLE_CONV_FAILED (75)
Character conversion failed.

CURLE_CONV_REQD (76)
Caller must register conversion callbacks.

CURLE_SSL_CACERT_BADFILE (77)
Problem with reading the SSL CA cert (path? access rights?)
CURLE_REMOTE_FILE_NOT_FOUND (78)
The resource referenced in the URL does not exist.

CURLE_SSH (79)
An unspecified error occurred during the SSH session.

CURLE_SSL_SHUTDOWN_FAILED (80)
Failed to shut down the SSL connection.

CURLE_AGAIN (81)
Socket is not ready for send/recv wait till it's ready and try again. This return code is only returned from curl_easy_recv(3) and curl_easy_send(3) (Added in 7.18.2)

CURLE_SSL_CRL_BADFILE (82)
Failed to load CRL file (Added in 7.19.0)

CURLE_SSL_ISSUER_ERROR (83)
Issuer check failed (Added in 7.19.0)

CURLE_FTP_PRET_FAILED (84)
The FTP server does not understand the PRET command at all or does not support the given argument. Be careful when using CURLOPT_CUSTOMREQUEST, a custom LIST command will be sent with PRET CMD before PASV as well. (Added in 7.20.0)

CURLE_RTSP_CSEQ_ERROR (85)
Mismatch of RTSP CSeq numbers.

CURLE_RTSP_SESSION_ERROR (86)
Mismatch of RTSP Session Identifiers.

CURLE_FTP_BAD_FILE_LIST (87)
Unable to parse FTP file list (during FTP wildcard downloading).

CURLE_CHUNK_FAILED (88)
Chunk callback reported error.

就本人遇到的问题,curl_errno()返回值是6,通过上述资料查询,得知原因是Couldn't resolve host. The given remote host was not resolved.即是“解析主机失败”的原因,至此,我就知道如何去进一步解决这个问题了。

此篇文章由DurkBlue发布,转载请注明来处
文章投稿或转载声明

来源:DurkBlue版权归原作者所有,转载请保留出处。本站文章发布于 2023-11-15
温馨提示:文章内容系作者个人观点,不代表DurkBlue博客对其观点赞同或支持。

赞(0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

阅读
分享