Skip to content

Instantly share code, notes, and snippets.

@wycks
Forked from franz-josef-kaiser/curl_dump.php
Last active December 11, 2015 12:18
Show Gist options
  • Save wycks/4599469 to your computer and use it in GitHub Desktop.
Save wycks/4599469 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: (#81791) Dump cURL Request & Response
* Author: Franz Josef Kaiser
*/
add_action( 'plugins_loaded', array( 'WPSE81791_cURL', 'init' ) );
class WPSE81791_cURL
{
protected static $instance;
public static $dump;
public static function init()
{
null === self :: $instance AND self :: $instance = new self;
return self :: $instance;
}
public function __construct()
{
add_action( 'http_api_curl', array( $this, 'dump_curl' ) );
add_action( 'shutdown', array( $this, 'do_dump' ) );
}
/**
* Debug the response in the middle.
* Catches the cURL object during the request.
* @param cURL $handle
* @return void
*/
public function dump_curl( &$handle )
{
curl_setopt( $handle, CURLINFO_HEADER_OUT, 1 );
curl_setopt( $handle, CURLOPT_HEADER, 0 );
curl_setopt( $handle, CURLOPT_HEADERFUNCTION, array( $this, 'dump_curl_buffer_cb' ) );
curl_setopt( $handle, CURLOPT_WRITEFUNCTION, array( $this, 'dump_curl_buffer_cb' ) );
curl_exec( $handle );
$this->add_dump(
curl_getinfo( $handle, CURLINFO_HEADER_OUT )
.$this->dump_curl_buffer_cb( null )
.'<br />Curl Error Code: '.curl_errno( $handle )
.'<br />Errors: '.curl_error( $handle )
);
}
/**
* Callback for cURL dump method
* @param object $curl
* @param null $data
* @return int
*/
public function dump_curl_buffer_cb( $curl, $data = null )
{
static $buffer = '';
if ( is_null( $curl ) )
{
$r = $buffer;
$buffer = '';
return $r;
}
$buffer .= $data;
return strlen( $data );
}
/**
* Adds data to the static data stack
* @param
* @return void
*/
public function add_dump( $data )
{
self :: $dump[] = $data;
}
/**
* Dumps the data stack for debug
* @param
* @return void
*/
public function do_dump()
{
! empty( self :: $dump ) AND printf(
'<pre>%s</pre>'
,var_export( implode( "<br />", self :: $dump ), true )
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment