Skip to content

Instantly share code, notes, and snippets.

@rajaishtiaq6
Forked from surferxo3/curl.php
Created May 4, 2023 22:19
Show Gist options
  • Save rajaishtiaq6/2be98b43dc4c4d24af40d6f795183086 to your computer and use it in GitHub Desktop.
Save rajaishtiaq6/2be98b43dc4c4d24af40d6f795183086 to your computer and use it in GitHub Desktop.
Script to demonstrate how to extract Header and Body from the Curl response in PHP.
<?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>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment