How to connecting to the remote site with CURL and header location - php

I am logging from site A through CURL on site B, I get the cookies from the connection and write to file called cookie.txt.
But when I pass the cookie data to do the final header redirection ('Location: http://examplesiteb.com'), it returns disconnected.
The code I am using for connection is the same as in this other post, but with my modifications following the #ramrider user's suggestion that I suggested passing the cookies in the header, but I'm not sure how this should be done.
Transfer cookies & session from CURL to header location
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 10);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
// Download the given URL, and return output
$output = curl_exec($ch);
// Cookie Match
preg_match_all('/^Set-Cookie:\s*([^\r\n]*)/mi', $output, $ms);
$cookies = array();
foreach ($ms[1] as $m) {
list($name, $value) = explode('=', $m, 2);
$cookies[$name] = $value;
header('Set-Cookie: '.rawurlencode($name).'='.rawurlencode($value));
}
//print_r($cookies);
$redirect = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
header("Location: $redirect");
//Close Match
curl_close($ch);
The redirect happens but does not keep logged in.
Below the example cookie file
# Netscape HTTP Cookie File
# http://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.
#HttpOnly_example.com FALSE / FALSE 0 ASP.NET_SessionId 10gtonkebkteuazx24sajlh2
#HttpOnly_example.com FALSE / TRUE 1515800212 DTE 898EC9C0EF0BA3985E402046547931EAA55808E14A2DE469F11F6F6C0CF9A28871C8704BE794885CDF7D3EE1E8B06698166F86C184C5B53FE61FA53CA13682C562E17BCB7B2FA16D7A7180E6EA973735
The users #martijn-pieters and #waqas-bukhary if they can help I thank you, because you deleted my answer in the other post, and I was completing with additional information for others that I can not find a solution.
Thanks

Cookies are tied to the domain that sends them. You cannot set cookies for a different domain.
If "Site B" (where you are using cURL to log in to "Site A") is example.com, and "Site A" is not-example.com, the cookies set by Set-Cookie are for example.com and will not apply to not-example.com.
There is no mechanism to set cookies for a domain other than your own.
See RFC 6265 Section 5.3 (Storage Model) Part 6:
If the domain-attribute is non-empty:
If the canonicalized request-host does not domain-match the domain-attribute:
Ignore the cookie entirely and abort these steps.
This effectively says that a browser must ignore a cookie if site A attempts to set a cookie for site B.

Related

PHP & cURL to use existing COOKIEFILE + Adding my own value to save

I already have a cookie file saved that I want to reference and update. I also want to specify my own additional cookie values via CURLOPT_COOKIE and save those to my existing cookie file as well.
However, I am unable to get this to work.
My code is:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $website); // Define target site
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Return page in string
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_COOKIE, "fruit=apple;");
curl_setopt($ch, CURLOPT_COOKIEJAR, "usercookies/cookie_$user.txt"); // Tell cURL where to write cookies
curl_setopt($ch, CURLOPT_COOKIEFILE, "usercookies/cookie_$user.txt"); // Tell cURL which cookies to send
curl_setopt($ch, CURLOPT_TIMEOUT,15);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follow redirects
$returnx = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
My saved cookie file does not reflect the changes I made via curl_setopt($ch, CURLOPT_COOKIE, "fruit=apple;");. The cookiefile saved should show "fruit=apple" but it's still showing the old values or the values returned by the cURL request.
Do I need to reference the entire domain name in order to get it to save?
The cookie file looks something like this:
# Netscape HTTP Cookie File
# http://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.
.go.com TRUE / FALSE 1754020486 one AE4F4981
.go.com TRUE / FALSE 1468965260 two B9A1
Cookies you add manually using CURLOPT_COOKIE won't get saved to the cookie jar at the end of the request.
The only case in which it would is if the server sent back a Set-Cookie header for the cookie you sent in order to update it.
The reason is because cURL requests have a cookie structure that holds cookies which gets written at the end of the request. Data only gets in this structure by a) being read from the cookie file in the first place or b) Set-Cookie headers in the response headers.
With a little care you can append your own cookie to that file with something like this:
$domain = '.go.com';
$expire = time() + 3600;
$name = 'fruit';
$value = 'apple';
file_put_contents($cookieJar, "\n$domain\tTRUE\t/\tFALSE\t$expire\t$name\t$value", FILE_APPEND);

PHP CURL script runs but it does not set the cookie

Im trying to set a cookie through PHP CURL for more than twenty four hour for no avail.
Before i have been setting cookies in my browser by adding them as parameters in a url as shown below
http://localhost/setc.php?userid=123&panelid=1
but now i need to set the cookie when i run a script(setcookie.php)
below is the latest of various types of code that i tried.
setcookie.php
$c = curl_init('http://localhost/atst.php?userid=628929&panelid=1');
curl_setopt($c, CURLOPT_VERBOSE, 1);
curl_setopt($c, CURLOPT_COOKIE, 'userid=123; panelid=1');
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$page = curl_exec($c);
curl_close($c);
it still does not create the cookie, can anybody help out
P.S : if you guys too cant figure this out at least give me a hint/guide on how to set a simple cookie without any complications
The cookiejar is only saved when you close the curl handle using curl_close($ch).
From the manual:
CURLOPT_COOKIEFILE The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.
CURLOPT_COOKIEJAR The name of a file to save all internal cookies to when the handle is closed, e.g. after a call to curl_close.
http://www.php.net/manual/en/function.curl-setopt.php
$ckfile = tempnam ("/tmp/", "CURLCOOKIE");
$BASEURL='http://localhost/openx/www/api/json/index.php/main/authenticate/';
$POSTFIELDS='username='.$username.'&password='.$password.'';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,'http://localhost/openx/www/api/json/index.php/main/authenticate/');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
ob_start(); // prevent any output
$result=curl_exec ($ch); // execute the curl command
ob_end_clean(); // stop preventing output
$result = curl_exec($ch);
curl_close($ch);

Sending a request with curl and a cookie loaded by the browser

I have got this code:
public function get_thead_page($cookie=null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_COOKIEFILE,'');
if($cookie) curl_setopt($ch, CURLOPT_COOKIE, $cookie);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Now I dont want to use my cookie value, but I want the browser to handle it for me. I wan tthe request to behave as if it was given by the browser.
So I want to the cookie to be loaded with the request instead of providing a value...
There is that value..
curl_setopt($ch, CURLOPT_COOKIEFILE,'');
which asks for the cookie file location...but I dont want to specify the location, I want the request to be sent with a cookie being loaded somehow without specifying the path on the system..
Is there any solution?
The browser can't do that. CURLOPT_COOKIEFILE refers to a server-side file which the browser have no access.
You're the one who made this app. It's to you to choose the cookie's location when you create it.

how to handle curl session and cookies in php

I want to login via curl and maintain the cookies and session information for further calls.i have created cookie text file in the same directory and used the CURLOPT_COOKIEJAR ,CURLOPT_COOKIEFILE to maintain the cookie in CUL. whenever i had try to call login api it take the old cookie and show the previous user information. i need to maintain different user cookies and maintain session like normal browser handle. how to do that. any one give idea to do it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER,0); // TRUE to include the header in the output.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // it will follow with server redirects
curl_setopt($ch,CURLOPT_AUTOREFERER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//ssl certificate verifyer
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //ssl certificate host
// Set the location of and send the cookies
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "/cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "/cookies.txt");
curl_setopt( $ch, CURLOPT_COOKIESESSION, true );
$result = curl_exec($ch); //execute curl and store data in result
You can modify
dirname(__FILE__) . "/cookies.txt"
Into something like
dirname(__FILE__) . '/user_cookies/' . $username . '.txt'
You will need to sanitize username for that line so that it will not contain any invalid characters.
Also, set /user_cookies/ permissions to something like 777.
This way you won't need to check if user has cookies or not. If not, the file will be created. If user has them, existing file content will be used.
You could also store cookies in database, but that's way more complicated.

How to make cURL not return on post

Im using cURL to post data to a php file (setcookie.php) on another domain.
The file, setcookie.php is supposed to set a cookie on that domain with the data posted to it.
The problem is the cookie doesn't want to be set when im doing it with cURL, because cURL returns to the calling file/domain, i guess.
So how can I make cURL not come back to the calling file?
Or is there an easier way to do this?
Here's my code :
$ch = curl_init ("http://<other domain>/setnewcookie.php");
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, false);
$returndata = curl_exec ($ch);
Here's what you need to do:
$ch = curl_init('http://example.org/setnewcookie.php');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
For cookies to work with cURL, you need to define both CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE. ALso, if you don't want the content of "http://example.org/setnewcookie.php" to be outputted to the browser, you need to set CURLOPT_RETURNTRANSFER to TRUE.
This will create a cookie on your server that cURL can use for subsequent requests but it won't allow the user of your website for instance to use that cookie. If the intent is for the user to be logged in on both sites, this will not work as-is.
For cross sub-domains (as in between www1.example.org and www2.example.org), have a look at PHP authentication with multiple domains and subdomains.
If you want the cookie to get sent from domain2 to browser, browser needs to make request directly.
So if you must get the information from domain1 and user must not get it directly, I'd somehow encrypt the data and redirect browser to send the request to domain2 like this:
domain1/script.php
$return_url = 'http://domain1/script2.php';
$request_url = 'http://domain2/setnewcookie.php';
$request = $request_url . '?data=' . url_encode($encrypted_data) . '&return_url=' . urlencode($return_url);
header('Location: ' . $request);
exit;
And then in domain2/setnewcookie.php just decrypt the data, set the cookie and once that is done, redirect user back to domain1 with help of the $return_url.
Still not sure if this was what you were trying to accomplish, HTH.

Categories