PHP CURL Cookie Jar
CURL stands for client URL, it is a tool for getting and sending data using various protocols, like - GET, POST, FTP, COOKIES, SMTP and many more. It uses libcurl library, which is portable and works identically on many different platforms. It also performs SSL certificate verification, when deal with HTTPs.
As we know, Cookies are pieces of content that are sent to a user's web browser. It allows us to store information on client browsers. The Cookie Jar is a simple cookie manager which automatically handle the HTTP Cookies. The curl can handle cookie specific tasks.
In cookiejar, we need to set a temporary file to hold the cookies and then, we can make subsequent requests that include those newly set cookies. To manage cookies with curl, we will use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE options in addition to the other options. The curl reads the cookies from the file and sends them along with the request.
The CURLOPT_COOKIEJAR contains the temporary filename where the cookies will be stored.
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
The CURLOPT_COOKIEFILE is used when CURL is written the cookie data back to the server.
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');
Complete Code: PHP CURL Cookie Jar
Here, first set a temporary file name to hold the cookies. You should be careful while storing the cookie jar because if another user can access this file. They can steal the stored credentials. You need to secure the access write to this file. Next, login to a login page using username and password and store in the cookie jar. After that, the user can make purchase and make payment to the portal.
<?php // A temporary file to hold the cookies $cookie_jar = tempnam('/tmp','cookie'); // log in $ch = curl_init('https://www.example.com/login.php?user=smith&password=sm@Th123'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar)); $page = curl_exec($ch); curl_close($ch); // purchase items $ch = curl_init('http://www.example.com/purchase.php?item=bookes'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar); $page = curl_exec($ch); curl_close($ch); // make payment $ch = curl_init('http://www.example.com/payment.php'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, 'item=bookes&amount=3000'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar); $page = curl_exec($ch); curl_close($ch); // remove the cookie jar unlink($cookie_jar) or die("Can't unlink $cookie_jar"); ?>
Related ArticlesPHP CURL GET and POST with Examples
How to add google reCAPTCHA v2 in registration form using PHP
Set and Get Cookies in PHP
Getting Document of Remote Address
jQuery loop over JSON result after AJAX Success
Simple star rating system using PHP, jQuery and Ajax
jQuery File upload progress bar with file size validation