PHP cURL cookies not saving on Windows
I was recently given a PHP application with the task of modifying it for increased efficiency. This application was originally written and executed only in a Linux environment. However I'm currently doing development on a Windows based computer.
Well, the modifications were going well, until it came time to execute cURL against a page which stores cookies. I was using the following code for this:
<?php $cr = curl_init($url); curl_setopt($cr, CURLOPT_COOKIEFILE, "./cookie.txt"); curl_setopt($cr, CURLOPT_COOKIEJAR, "./cookie.txt");
But for some reason the cookie.txt file was not being updated. In an attempt at trouble shooting, I checked to see if Apache/PHP had write permissions on this file, so I touched the file using php (which updates the timestamp or creates a blank file if it does not exist):
PHP was able to create the file, however cURL was still not writing to it! The cURL library is distributed on Linux machines as a separate binary from PHP which can be executed on the command line, meaning that cURL was not built into PHP/Apache.
Finally I realized that perhaps PHP did not send cURL the current working directory of the script that it was in, making the relative paths being sent to cURL useless. But, nobody wants to hard code paths into their applications, this makes it harder to expand the program and difficult to find all paths when moving the script. So, I set up the script to pull the current full location of the script that was executing the cURL instance, which would be sent to cURL as the path to sake the cookies in. Here are the updates to the cURL function calls to make it execute properly on a windows machine:
<?php $cr = curl_init($url); curl_setopt($cr, CURLOPT_COOKIEFILE, dirname(__FILE__) . "/cookies.txt"); curl_setopt($cr, CURLOPT_COOKIEJAR, dirname(__FILE__) . "/cookies.txt");