PHP CURL Function Example

This function is populated with all needed data for curl to be executed

function get_curl($site_url){
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $site_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');

    $headers = array();
    $headers[] = "Accept-Encoding: gzip, deflate, sdch";
    $headers[] = "Accept-Language: en-US,en;q=0.8";
    $headers[] = "Upgrade-Insecure-Requests: 1";
    $headers[] = "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36";
    $headers[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
    $headers[] = "Referer: $site_url";
    //Set a cookie if needed (you can set other values)
    $headers[] = "Cookie: D_SID=185.196.133.50:u147oywWqvEJoD/GIlY10erXbeio1QIKGdi6Vo6/HVo; D_IID=0108BE8F-6C68-31CF-9B9D-4308308DB3A6; D_UID=5A4BCE68-9FD2-3A70-B1DF-376B7D77FD4B; D_ZID=248B7EFC-E23A-3F71-A675-764EA373AEC6; D_ZUID=4DFFC8BD-0AD9-3DE0-94AE-60A57D49736A; D_HID=07EDD9E4-1EDF-3EE3-9D52-B67B5952F6EC";
    $headers[] = "Connection: keep-alive";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);

    if (curl_error($ch)) {
        $output['status'] = '404';
        $output['msge'] = curl_error($ch);
    } else {
        $output['status'] = 'ok';
        $output['html'] = $result;
    }

    curl_close ($ch);
    return $output;
}

Send Array to API with POST

function send_curl(array $array)
    {

        $api = 'https://localhost/services/api';
        $action = 'test';
        $password = 'TestPass';

        $ch = curl_init($api);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(
            [
                'password' => $password ,
                'data' => $array,
                'action' => $action,
            ]
        ));
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $serverOutput = curl_exec($ch);
        curl_close($ch);

        return $serverOutput;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *