当前位置 : 主页 > 网络编程 > PHP >

curl模拟提交.php

来源:互联网 收集:自由互联 发布时间:2021-06-28
curl模拟提交.php /** * curl 方式模拟get,post 提交 * */ /** * get提交 * * @author gaoxianlei * @date 2017/07/24 * * @param string $url 地址 * @param array $params 参数 * @param string $cookie cookie * @param boolean $raw 是否
curl模拟提交.php
/**
 * curl 方式模拟get,post 提交
 *
 */

     /**
     * get提交
     *
     * @author gaoxianlei
     * @date   2017/07/24
     *
     * @param  string   $url      地址
     * @param  array    $params   参数
     * @param  string   $cookie   cookie
     * @param  boolean  $raw      是否解码json
     *
     * @return string
     */
    private function _get_json_data($url = '', $params = [], $raw = false, $cookie = '')
    {
        $paramsString = $params ? http_build_query($params, '', '&', 2) : '';
        $fullUrl = $url . '?' . $paramsString;

        return $this->_http_request($fullUrl, [], $raw, $cookie);
    }

    /**
     * post提交
     *
     * @author gao
     * @date 2017/07/24
     *
     * @param  string    $url     地址
     * @param  array     $params  参数
     * @param  string    $cookie  cookie
     * @param  boolean   $raw     是否解码json
     *
     * @return string
     */
    private function _post_json_data($url = '', $params = [], $raw = false, $cookie = '')
    {
        return $this->_http_request($url, $params, $raw, $cookie);
    }

    /**
     * curl 模拟提交
     *
     * @author gao
     * @date 2017/07/24
     *
     * @param string   $url     访问的URL
     * @param array    $post    post数据(不填则为GET)
     * @param string   $cookie  提交的$cookies
     * @param boolean  $raw     是否解码json
     *
     * @return string
     */
    private function _http_request($url, $post = [], $raw = false, $cookie = '')
    {
        //Initiate cURL request and send back the result
        $ch = curl_init();
        if (!$post) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if ($post) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        if ($cookie) {
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }
        $result = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($code == 200) {
            return $raw ? json_decode($result, true) : $result;
        }

        return false;
    }
上一篇:index.html
下一篇:sendMsg.php
网友评论