Sorry! Internet Explorer is not supported on this site. Please view on Chrome, Firefox, or Edge.

Having fun at Zao is one of our values. We’ve put limited animated flourishes throughout our site to communicate our love of levity. We also recognize that onscreen movement is not fun or possible for everyone. We've turned off all our animations for you per your browser's request to limit motion. That said, we don't want you to miss out on the party.

Here's a funny joke to enjoy!

Where does the General keep his armies?

In his sleevies!

Using Cookies in the WP HTTP API for Admin Requests

I had an interesting need to have authenticated admin requests over HTTP.  A few different plugins were creating output on admin pages.  I needed to capture that output, HTML and all, and save it into PDFs.  I’ll save the whole HTML-to-PDF discussion for another day – but what was interesting was figuring out how to serve these HTML pages in an admin request.

There was a lot of moving pieces, so the best way (in my mind) to serve this HTML was over an HTTP request, rather than try to piece together all of the functions and views from each different plugin that were producing the output.  Naturally, the following code presented me with a login form.

$link = 'http://site.com/wp-admin/index.php?page=page';

$args = array();

var_dump( wp_remote_get( $link, $args ) );

That was expected.  I assumed I would need to pass the cookies in the second parameter of the wp_remote_get() request.  I tried the following, expecting it to work:

$link = 'http://site.com/wp-admin/index.php?page=page';

$cookies = array();
foreach ( $_COOKIE as $name => $value ) {
    $cookies[] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value ) );
}

$args = array( 'cookies' => $cookies );

var_dump( wp_remote_get( $link, $args ) );

Doing this gave me an expected error. An ‘http_request_failed’ error with the following text: “Operation timed out after 4 seconds with 0 bytes received”.

Thinking that was odd, I checked out the cookies that were being passed and began tweaking.  Removing the PHPSESSID cookie did the trick.  Check it out:

$link = 'http://site.com/wp-admin/index.php?page=page';

$cookies = array();
foreach ( $_COOKIE as $name => $value ) {
    if ( 'PHPSESSID' !== $name ) {
        $cookies[] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value ) );
    }
}

$args = array( 'cookies' => $cookies );

var_dump( wp_remote_get( $link, $args ) );

Pretty neat.  Not the first time I’ve run into this problem, but definitely the most effective way I’ve solved it.

Join the Conversation

2 Comments

Leave a comment

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