Php curl setting cookie

PHP CURL With Cookies (Simple Examples)

Welcome to a tutorial on how to do PHP CURL calls with cookies. Need to do a server-to-server call that involves cookies? Well yes, CURL is fully capable of handling that with a few small tweaks.

To do a PHP CURL call with cookies, we use CURLOPT_COOKIEJAR to specify where to save the cookie after the call ends, and CURLOPT_COOKIEFILE to specify which cookie file to send to the remote server.

  • $cookie = «COOKIE.TXT»;
  • $ch = curl_init();
  • curl_setopt($ch, CURLOPT_URL, «HTTP://SITE.COM»);
  • curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
  • curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
  • curl_exec($ch);
  • curl_close($ch);

That covers the basics, but read on for more examples!

TLDR – QUICK SLIDES

PHP CURL With Cookies

TABLE OF CONTENTS

PHP CURL COOKIES

All right, let us now get into the examples of handling cookies with PHP CURL.

1A) LOCAL SERVER CURL CALL

This is just a “slightly improved” version of the introduction snippet to output the exchange results between the local and remote servers.

Читайте также:  text-transform

1B) DUMMY REMOTE SERVER

On the dummy remote server – We simply output the received cookie and send a header to set the Test cookie to the current timestamp.

1C) WHAT WILL HAPPEN

  • On the first run –
    • The remote server will not show any cookie values since it is a new connection.
    • The remote server then responds with a set-cookie Test = NOW back to the local server.
    • The local server saves Test = NOW to the cookie.txt file.
    • The local server reads cookie.txt and sends it to the remote server.
    • The remote server now displays the timestamp of the previous visit.
    • Then sends set-cookie Test = NOW back to the local server.
    • The local server updates Test = NOW in the cookie.txt file.

    2) MANUALLY SETTING COOKIES

    • The local server will read from cookie.txt , append keyA=valueA; keyB=valueB , and send these to the remote server.
    • The remote server will now show the cookie values of Test, keyA, keyB .
    • Take note of the response part – The remote server only states set-cookie Test = NOW . So the local server will only update Test in cookie.txt ; keyA keyB will not be saved.

    3) FLUSHING & CLEARING COOKIES

    // (C) FORCE NEW SESSION // CURLOPT_COOKIESESSION - FORCE NEW COOKIE SESSION, IGNORE LAST curl_setopt($ch, CURLOPT_COOKIESESSION, true); // CURLOPT_COOKIELIST // "ALL" ERASES ALL COOKIES IN MEMORY. // "SESS" ERASES ALL SESSION COOKIES HELD IN MEMORY. // "FLUSH" WRITES COOKIES TO CURLOPT_COOKIEJAR. // "RELOAD" RELOAD COOKIES FROM CURLOPT_COOKIEFILE. curl_setopt($ch, CURLOPT_COOKIELIST, "ALL");

    Lastly, just a quick mention – If you need to clear or empty the cookies, use the CURLOPT_COOKIESESSION or CURLOPT_COOKIELIST options to do it.

    DOWNLOAD & NOTES

    Here is the download link to the example code, so you don’t have to copy-paste everything.

    SUPPORT

    600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

    EXAMPLE CODE DOWNLOAD

    Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

    That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.

    INFOGRAPHIC CHEAT SHEET

    THE END

    Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

    Leave a Comment Cancel Reply

    Breakthrough Javascript

    Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

    Socials

    About Me

    W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

    Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

    Источник

    PHP cURL Part 6(Cookies saving and sending)

    So far, we’ve learned the following features of PHP cURL in this series of articles.

    In this article, we’ll learn how to perform save & send cookies using PHP cURL. Sometimes websites use cookies to save user-specific information and then use those saved cookies to load resources for users. So, in this case, we can’t access website resources directly. We first need to get cookies from that site and then we’ll send those cookies in our upcoming cURL requests. Following is a very basic example for cookies.

    $cookie_jar = tempnam('/tmp','coo'); // getting cookies $curl = curl_init('http://httpbin.org/cookies/set?site=coderanks'); curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($curl); curl_close($curl); //sending cookies $curl = curl_init('http://httpbin.org/cookies'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_jar); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); curl_close($curl); echo '
    ',$response; 

    Response:

    Explanation:

    In the above script, we've performed the following three steps.

    1. Creating a temporary file to save cookies
    2. Getting cookies and saving in the file(created in the first step)
    3. Using cookies(saved in the second step) for a new curl request.

    Let's discuss each step in details with code.

    Creating a temporary file to save cookies

    We need to save cookies somewhere for future use, so for this, we're going to create a temporary file. This step can be with the following piece of code.

    $cookie_jar = tempnam('/tmp','coo');

    tempnam is a built-in PHP function that is used to create a unique empty file. Its first parameter is file path(default is System's directory) and the second parameter is the prefix of the file. So it will create a file in C:\Windows\Temp with a unique name prefixed with coo and will return its full path. Here is an example file created by tempname.

    Getting cookies and saving in the file

    Temporary file created in the first step will be empty. Now, in this step, we'll get cookies from URL and will save them in that file. Following piece of code will help us to do that.

    // getting cookies $curl = curl_init('http://httpbin.org/cookies/set?site=coderanks'); curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($curl); curl_close($curl);

    Following options are already discussed in previous parts. Here is a simple detail for both options.

    1. CURLOPT_RETURNTRANSFER: used to direct cURL to not display response(default) but return after execution.
    2. CURLOPT_SSL_VERIFYPEER: used to enable or disable SSL.

    CURLOPT_COOKIEJAR

    This option is used to set the cookies file, which will be used by the cURL to save automatically parsed cookies.

    So after executing the above script, there will be some text in that file, similar to below one.

    # Netscape HTTP Cookie File # https://curl.haxx.se/docs/http-cookies.html # This file was generated by libcurl! Edit at your own risk. httpbin.org FALSE / FALSE 0 site coderanks 

    Using cookies for a curl request

    Now we've cookies saved in a file, we can use that file to send cookies for any cURL request. here is the script for sending cookies.

    //sending cookies $curl = curl_init('http://httpbin.org/cookies'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_jar); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); curl_close($curl); echo '
    ',$response; 

    CURLOPT_COOKIEFILE is used to set the cookies file to attach cookies in the cURL request. Here is the response to this request.

    Note: Normal sites don't return cookies when you send them. We've used Httpbin.org for the testing purpose of this article to show you that how actually cookies saved and passed. In the real-life example, you'll pass cookies and get the site resources after executing, not cookies.

    That's all for this part of the article.

    Источник

Оцените статью