One question: is the 3rd party that’s sending the request passing a user cookie?
If not, then WP will treat the request like any other guest! If it is, have you inspected $_COOKIE
when send_response()
runs?
Update: Thought I’d try and wrap up the discussion below, once and for all 🙂
You’ll have to maintain a database log of signed-in users
I thought WP was doing that already!
No, WP simply validates the cookie (if one was sent) on each request.
I thought the cookies were stored in the browser
Yup.
So if the same user is logged into my site, and then visits the sub-domain site, which calls file_get_contents(), why aren’t the cookies there?
Because the API request originates from the server, not the browser. That’s like asking why you’re not logged in with Chrome after you signed in using Firefox!
I’d like to retract my suggestion about maintaining a log of sign-ins, since I believe there are two better, easier solutions;
- Fire the request on the client-side (i.e. with AJAX) – since it originates from the user’s brower, the cookies are sent along as you would expect
- Send the user’s cookie along with your API request on the server side* (see below)
Example code for sending remote get with client’s cookies:
$data = array();
if ( ! empty( $_SERVER['HTTP_COOKIE'] ) ) {
foreach ( explode( '; ', $_SERVER['HTTP_COOKIE'] ) as $pair )
$data['cookies'][] = new WP_Http_Cookie( $pair );
}
// Wp_Http_Cookie will choke if cookie value has special characters.
add_filter( 'wp_http_cookie_value', 'rawurlencode' );
if ( $get = wp_remote_get( $url, $data ) ) {
// Yippee!
}
However, 2) comes with a catch; the cookies needed to validate the API request must be sent to the script that fires it (the mention of subdomains flags a potential problem here).
If you’re using MultiSite with subdomains, this is taken care of. Otherwise, you’ll need to force the cookie domain in your wp-config.php
:
define( 'COOKIE_DOMAIN', '.example.com' );
See that dot prefix? This indicates that the cookie should be sent to the domain or any of it’s subdomains (whereas by default, WP will set it to apply only to the main domain).