博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

dnspod CURL模拟访问

Posted on 2021-01-29 13:18  PHP-张工  阅读(196)  评论(0编辑  收藏  举报

使用CURL模拟访问网页,保留返回的COOKIE

<?php

class dnspod {
    public static function api_call($api, $data) {
        $api = 'https://dnsapi.cn/' . $api;
        echo $api . PHP_EOL;
        $data = array_merge($data, [
            'login_token'    => TOKEN,
            'format'         => 'json', 
            'lang'           => 'cn', 
            'error_on_empty' => 'no',
        ]);

        $result = self::post_data($api, $data, $_SESSION['cookies']);
        if (!$result) {
            return false;
        }

        $result = explode("\r\n\r\n", $result);
        if (preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result[0], $cookies)) {
            foreach ($cookies[1] as $key => $value) {
                if (substr($value, 0, 1) == 't') {
                    $_SESSION['cookies'] = $value;
                }
            }
        }

        $results = @json_decode($result[1], 1);
        if (!is_array($results)) {
            return false;
        }

        if ($results['status']['code'] != 1) {
            return $results['status']['message'];
        }

        return $results;
    }

    private static function post_data($url, $data, $cookie='') {
        $ch = @curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_USERAGENT, 'DNSPod API PHP Web Client/1.0.0 (i@likexian.com)');
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }
}