开发者

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 proble开发者_Python百科m 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜