Send cookie with file_get_contents
#3
Cookie: user=3345; pass=abcd
Cookies are not being sent with file_get_contents or CURL requests
The headers may need to be separated by \r\n
rather than just \n
. You can also use an array, and they'll be sent properly.
'header' => array("Content-Type: application/x-www-form-urlencoded",
"Cookie: session_hash=123456789")
How to send cookies with file_get_contents
First, this is probably just a typo in your question, but the third arguments to file_get_contents() needs to be your streaming context, NOT the array of options. I ran a quick test with something like this, and everything worked as expected
$opts = array('http' => array('header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE']."\r\n"));
$context = stream_context_create($opts);
$contents = file_get_contents('http://example.com/test1.txt', false, $context);
echo $contents;
The error indicates the server is returning a 404. Try fetching the URL from the machine PHP is running on and not from your workstation/desktop/laptop. It may be that your web server is having trouble reaching the site, your local machine has a cached copy, or some other network screwiness.
Be sure you repeat your exact request when running this test, including the cookie you're sending (command line curl is good for this). It's entirely possible that the page in question may load fine in a browser without the cookie, but when you send the cookie the site actually is returning a 404.
Make sure that $_SERVER['HTTP_COOKIE'] has the raw cookie you think it does.
If you're screen scraping, download Firefox and a copy of the LiveHTTPHeaders extension. Perform all the necessary steps to reach whatever page it is you want in Firefox. Then, using the output from LiveHTTPHeaders, recreate the exact same request requence. Include every header, not just the cookies.
Finally, PHP Curl exists for a reason. If at all possible, (I'm not asking!) use it instead. :)
file_get_contents receive cookies
you should use cURL
for that purpose, cURL
implement a feature called the cookie jar which permit to save cookies in a file and reuse them for subsequent request(s).
Here come a quick code snipet how to do it:
/* STEP 1. let’s create a cookie file */
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
/* STEP 2. visit the homepage to set the cookie properly */
$ch = curl_init ("http://somedomain.com/");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
/* STEP 3. visit cookiepage.php */
$ch = curl_init ("http://somedomain.com/cookiepage.php");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
note: has to be noted you should have the pecl extension (or compiled in PHP) installed or you won't have access to the cURL API.
file_get_contents get Cookies
According to php.net:
$http_response_header will be created in the local scope.
Because of this $http_response_header
is available only in the scope of get()
.
You can pass it like $this->get_cookies($http_response_header);
or create a property to store it.
How to use file_get_contents() with a Wordpress user's cookies
It turns out I was doing it correctly, but I didn't know that WP needs a second cookie sent in order for the request to work properly.
Here's the code that works for me:
$cookies = $_COOKIE;
$name;
$value;
foreach ($_COOKIE as $key => $cookie ) {
if ( strpos( $key, 'wordpress_logged_in') !== FALSE ) {
$name = $key;
$value = $cookie;
}
}
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: {$key}={$cookie}; wordpress_test_cookie=WP Cookie check \r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://mydomain.dev/api/autho/', false, $context);
var_dump($file);
It's basically the same thing as you see in my question, but with an important addition: wordpress_test_cookie=WP Cookie check
. I haven't seen it documented anywhere, but WP needs this cookie as well as the actual wordpress_logged_in cookie in order for the call to happen as an logged in user.
Php file_get_contents not capturing certain group of cookies
Several items to incorporate to solve this.
1. moved to curl
2. remove content length (this caused redirect following to timeout everytime when set)
3. Make a second request and store the cookie and present all stored cookies.
Had to use all the options below
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "",
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_COOKIEJAR => 'cookie.txt',
CURLOPT_COOKIEFILE => 'cookie.txt',
CURLOPT_SSL_VERIFYPEER => false,
Related Topics
Laravel's 5.3 Passport and API Routes
Select Within 20 Kilometers Based on Latitude/Longitude
How to Remove the Last Comma from a String Using PHP
How to Get the Last Path in a Url
How to Install the Intl Extension for Twig
How to Detect If Have to Apply Utf-8 Decode or Encode on a String
PHP & MySQL: When Exactly to Use HTMLentities
Error 405 (Method Not Allowed) Laravel 5
Use PHP Namespace Inside Function
File_Get_Contents() How to Fix Error "Failed to Open Stream", "No Such File"
Uncompress a Gzip File from Curl, on PHP
PHP Date Format Yyyy-Mm-Dd Minus or Add One Week from Now
Aggregated Query Without Group By
How to Get Array Key from Corresponding Array Value
Browser Displays � Instead of '
Rsa Encryption/Decryption Compatible with JavaScript and PHP