Skip to content

Instantly share code, notes, and snippets.

@catwhocode
Forked from surferxo3/curl.php
Created March 15, 2024 00:43
Show Gist options
  • Select an option

  • Save catwhocode/2cd5b352d19dcf1ec796c27f8616e370 to your computer and use it in GitHub Desktop.

Select an option

Save catwhocode/2cd5b352d19dcf1ec796c27f8616e370 to your computer and use it in GitHub Desktop.

Revisions

  1. @surferxo3 surferxo3 revised this gist Feb 5, 2018. No changes.
  2. @surferxo3 surferxo3 created this gist Dec 17, 2016.
    73 changes: 73 additions & 0 deletions curl.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,73 @@
    <?php

    /*#############################
    * Developer: Mohammad Sharaf Ali
    * Designation: Web Developer
    * Version: 1.0
    */#############################

    // SETTINGS
    ini_set('max_execution_time', 0);
    ini_set('memory_limit', '1G');
    error_reporting(E_ERROR);

    // HELPER METHODS
    function initCurlRequest($reqType, $reqURL, $reqBody = '', $headers = array()) {
    if (!in_array($reqType, array('GET', 'POST', 'PUT', 'DELETE'))) {
    throw new Exception('Curl first parameter must be "GET", "POST", "PUT" or "DELETE"');
    }

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $reqURL);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $reqType);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $reqBody);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_HEADER, true);

    $body = curl_exec($ch);

    // extract header
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($body, 0, $headerSize);
    $header = getHeaders($header);

    // extract body
    $body = substr($body, $headerSize);

    curl_close($ch);

    return [$header, $body];
    }

    function getHeaders($respHeaders) {
    $headers = array();

    $headerText = substr($respHeaders, 0, strpos($respHeaders, "\r\n\r\n"));

    foreach (explode("\r\n", $headerText) as $i => $line) {
    if ($i === 0) {
    $headers['http_code'] = $line;
    } else {
    list ($key, $value) = explode(': ', $line);

    $headers[$key] = $value;
    }
    }

    return $headers;
    }

    // MAIN
    $reqBody = '';
    $headers = array();

    list($header, $body) = initCurlRequest('GET', 'https://www.google.com.pk', $reqBody, $headers);

    echo '<pre>';
    print_r($header);
    print_r($body);
    echo '</pre>';