13.3.1. ProblemYou want to retrieve a page that requires a cookie to be sent with the request for the page. 13.3.2. SolutionUse the CURLOPT_COOKIE option with cURL, as shown in Example 13-17. Sending cookies with cURL
With HTTP_Request, use the addHeader( ) method to add a Cookie header, as shown in Example 13-18. Sending cookies with HTTP_Request
13.3.3. DiscussionCookies are sent to the server in the Cookie request header. The cURL extension has a cookie-specific option, but with HTTP_Request, you have to add the Cookie header just as with other request headers. Multiple cookie values are sent in a semicolon-delimited list. The examples in the Solution send two cookies: one named user with value ellen and one named activity with value swimming. To request a page that sets cookies and then make subsequent requests that include those newly set cookies, use cURL's "cookie jar" feature. On the first request, set CURLOPT_COOKIEJAR to the name of a file to store the cookies in. On subsequent requests, set CURLOPT_COOKIEFILE to the same filename, and cURL reads the cookies from the file and sends them along with the request. This is especially useful for a sequence of requests in which the first request logs into a site that sets session or authentication cookies, and then the rest of the requests need to include those cookies to be valid. Example 13-19 shows such a sequence of requests. Tracking cookies with cURL's cookie jar
Be careful where you store the cookie jar. It needs to be in a place your web server has write access to, but if other users can read the file, they may be able to poach the authentication credentials stored in the cookies. HTTP_Client offers a similar cookie-tracking feature. You don't have to do anything special to enable it. If you make multiple requests with the same HTTP_Client object, cookies are automatically preserved from one request to the next. 13.3.4. See AlsoDocumentation on curl_setopt( ) at http://www.php.net/curl-setopt; the PEAR HTTP_Request class at http://pear.php.net/package/HTTP_Request, the PEAR HTTP_Client class at http://pear.php.net/package/HTTP_Client; "Persistent Client State - HTTP Cookies" at http://wp.netscape.com/newsref/std/cookie_spec.html and "HTTP Cookies: Standards, Privacy, and Politics" by David M. Kristol at http://arxiv.org/abs/cs.SE/0105018. |