I'm dumbfounded as to how this edit actually got declined. Maybe you can enlighten me. The question was how to pass cookies in a file_get_contents()
call - link here https://stackoverflow.com/review/suggested-edits/11304370 . The OP answered his own question here:
I just used curls instead of file_get_contents and everything works well with me:
function request_url($method='get', $vars='', $url) { $ch = curl_init(); if ($method == 'post') { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies/cookies.txt'); curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies/cookies.txt'); $buffer = curl_exec($ch); curl_close($ch); return $buffer; }
So I appended this to the bottom, since I felt his answer may not help someone who's new to coding actually grasp why cURL works, and what this code sample is actually doing. Here's my appended edit:
The magic happens with CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE.
CURLOPT_COOKIEJAR tells cURL to write all internally known Cookies to the specified file. In this case, 'cookies/cookies.txt'. For most users, it's generally recommended to use something like tempnam('/tmp', 'CURLCOOKIES') so you know for sure that you can generate this file.
CURLOPT_COOKIEFILE tells cURL which file to use for Cookies during the cURL request. That's why we set it to the same file we just dumped the Cookies to.
According to those approving/denying, I was addressing the author. Please, enlighten me, how am I addressing the author with this edit? What could possibly be addressing anyone inside this edit, other than those who could stumble upon this and wonder why this code works? I wanted to be clear that cookies don't just work simply because you're using cURL.
Here's my comment:
Comment: A bit more explanation for anyone stumbling upon this answer who do not know exactly how or why cURL works with Cookies.