Im using MAMP on a Mac running OS X Lion.
I need to connect to a remote site sending the cookie.
All goes well except for the cookie part.
For the cookie part I'm using this code:
$cookieFile = dirname(__FILE__).'/cookie.txt';
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
The CURLOPT_COOKIEJAR part does create a cookie, but on a subsequent request CURLOPT_COOKIEFILE doesn't add a cookie header. I've checked this using HTTPScoop (a Fiddler like tool).
Any idea what might be the problem?
EDIT:
Im connecting to a ASP.Net site. Problem seems to be the im not getting a ASP.NET_SessionId cookie. The cookie i do get has a key without a value, thats probably the reason why it isn't posted.
Any idea how to force the server to send a session cookie?
We'd really need to see more code, but here is a sample bit I have which collects a session cookie from an initial request then uses it in a subsequent POST. It uses an anonymous proxy to run a GET request on an arbitrary URL, hopefully it helps you (to be clear though it doesn't use the COOKIEJAR, but I feel it may still be helpful).
<?php
define('TARGET_URL', 'http://moxune.com');
echo 'Sending initial request' . PHP_EOL;
$aHeaders = get_headers("http://420proxy.info");
foreach($aHeaders as $sHeader) {
if(stripos($sHeader, 'set-cookie') !== false) {
// extract the cookie from the first response
$aCookie = explode(':', $sHeader);
$sCookie = trim(array_pop($aCookie));
$oCookie = http_parse_cookie($sCookie);
echo 'Cookie extracted, trying to POST now' . PHP_EOL;
// OK, now let's try the POST request
$ch = curl_init('http://420proxy.info/includes/process.php?action=update');
curl_setopt($ch, CURLOPT_REFERER, '420.proxy.info');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_COOKIE, $sCookie);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: 100-continue'));
//curl_setopt($ch, CURLOPT_COOKIE, http_build_cookie((array)$oCookie));
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'u' => TARGET_URL,
'allowCookies' => 'off',
'encodeURL' => 'off',
'stripJS' => 'on'
)
);
$response = curl_exec($ch);
die(var_dump($response));
}
}
Related
I'm building an application using a local php file that takes post/get input and returns JSON results. I'm doing this to de-couple front and backend operation on the idea that it's possible to move the backend elsewhere eventually (and it's neat because you can test backend operation using only browser and URL variables.
To be clear, I have no immediate or even long-term plans to actually separate them: right now they're on the same server in the same folder even - I just have a single backend.php file pretending to be a remote server so that I can practice decoupling. Victory for this issue means calling CURL and having the backend recieve the session, the backend can change/update/addto the session, and the front end sees all changes (basically ONE session for front and back).
The problem is that I'm constantly fighting to get session to work between the two. When I make AJAX requests with Javascript, session works fine because it's a page loading on the same server so session_start() just works. But when I CURL, the session data is not transferred.
I've been fighting with this for months so my curl function is pretty messy, but I can't figure out the magic combination that makes this work. No amount of SO questions or online guides I've been able to find work consistently in this case:
// Call the backend using the provided URL and series of name/value vars (in an array)
function backhand($data,$method='POST') {
$url = BACKEND_URL;
// Make sure the backend knows which session in the db to connect to
//$data['session_id'] = session_id();
// Backend will send this back in session so we can see the the connection still works.
//$data['session_test'] = rand();
$ch = curl_init();
if ('POST' == $method) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$get_url = sprintf("%s?%s", $url, http_build_query($data));
$_SESSION['diag']['backend-stuff'][] = $get_url;
if ('GET' == $method) {
curl_setopt($ch, CURLOPT_PUT, 1);
$url = $get_url;
}
// Optional Authentication:
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
# curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
# curl_setopt($ch, CURLOPT_VERBOSE, 1);
# curl_setopt($ch, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
// Retrieving session ID
// $strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
$fh = fopen($cookieFile, "w");
fwrite($fh, $_SESSION);
fclose($fh);
}
#curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
#curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
#curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
// We pass the sessionid of the browser within the curl request
curl_setopt( $ch, CURLOPT_COOKIEFILE, $strCookie );
# session_write_close();
// Have to pause the session or the backend wipes the front
if (!$result = curl_exec($ch)) {
pre_r(curl_getinfo($ch));
echo 'Cerr: '.curl_error($ch);
}
curl_close($ch);
# session_start();
// "true" makes it return an array
return json_decode($result,true);
}
I call the function like so from the front-end to get results from the backend:
// Get user by email or ID
function get_user($emailorid) {
// If it's not an email, see if they've been cached. If so, return them
if (is_numeric($emailorid) && $_SESSION['users'][$emailorid])
return $_SESSION['users'][$emailorid];
return backhand(['get_user'=>$emailorid]);
}
So if I call "get_user" anywhere in the front, it will hop over to the back, run the db queries and dump it all to JSON which is returned to me in an associative arrays of values. This works fine, but session data doesn't persist properly and it's causing problems.
I even tried DB sessions for a while, but that wasn't consistent either. I'm running out of ideas and might have to build some kind of alternate session capability by using the db and custom functions, but I expect this CAN work... I just haven't figured out how yet.
You could keep the file system storage and share the file directory where are stored session with NFS if your backend web servers are on different servers.
You could also use http://www.php.net/manual/en/function.session-set-save-handler.php to set a different save handler for your session, but I am not sure that storing them on a database would be a good idea for I/O.
After brute-force trial and error, this seems to work:
function backhand($data,$method='POST') {
$url = BACKEND_URL;
// Make sure the backend knows which session in the db to connect to
//$data['session_id'] = session_id();
// Backend will send this back in session so we can see the the connection still works.
$data['session_test'] = rand();
$ch = curl_init();
if ('POST' == $method) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$get_url = sprintf("%s?%s", $url, http_build_query($data));
$_SESSION['diag']['backend-stuff'][] = $get_url;
if ('GET' == $method) {
curl_setopt($ch, CURLOPT_HTTPGET, 1);
$url = $get_url;
}
// Optional Authentication:
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
// required or it writes the data directly into document instead of putting it in a var below
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
#curl_setopt($ch, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
// Retrieving session ID
$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
// We pass the sessionid of the browser within the curl request
curl_setopt( $ch, CURLOPT_COOKIE, $strCookie );
curl_setopt($ch, CURLOPT_COOKIEJAR, 'somefile');
curl_setopt($ch, CURLOPT_COOKIEFILE, APP_ROOT.'/cookie.txt');
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
// Have to pause the session or the backend wipes the front
session_write_close();
if (!$result = curl_exec($ch)) {
pre_r(curl_getinfo($ch));
echo 'Cerr: '.curl_error($ch);
}
#session_start();
curl_close($ch);
// "true" makes it return an array
return json_decode($result,true);
}
I have seen some of the questions that others have asked regarding this same issue but I don't seem to be having much luck in my situation and would appreciate some clarification.
I need to pass a session variable from domain1.com to domain2.com. I have full access to both domains. I am using cURL to have domain1.com/caller.php access domain2.com/receiver.php. Once cURL finishes executing I get a status returned. If that status is good I use header("Location: auto_submit.html") to load a page that automatically submits a form/redirects to domain2.com/test.php. However when the page loads the session variable is not set. Here is what I have in domain1.com/caller.php
...
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "domain2.com/receiver.php");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $result[0]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER , true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');
$curl_result = json_decode(curl_exec($ch));
curl_close($ch);
if ($curl_result->status === 1)
{
header("Location: ./auto_submit.html");
exit;
} else {
foo();
}
...
auto_submit.html just redirects to domain2.com/test.php.
What, if anything, do I need on domain2.com/test.php so that it will use the information in the cookie file and will be accessible in $_SESSION?
I bother with sending additional coockies to server. I'm receiving coockies from server uses to connecting with success but when i try to add more data in coockie, server do not receive it. I tried few ways to fix it but now im tired and devoid of ideas. Looking forward for your any helpful replies!
Here is the code:
$cookie = 'var1='.urlencode($config['log']);
curl_setopt($ch, CURLOPT_COOKIE, $cookie); curl_setopt($ch, CURLOPT_URL, 'https://locaIp.adress/'); curl_setopt($ch, CURLOPT_POSTFIELDS, array('var1' => $config['log'],); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $echo = curl_exec($ch); </i>
HttpOnly was my initial pick, but you said that you post one var, but no multiple (I'm guessing that's what you mean adding more data). If that's the issue it should be preparing the data before you send it.
$cookie = 'log1='.urlencode($config2['log1']).";".'log2='.urlencode($config2['log2']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIE, $cookie ); // it works like this
//curl_setopt($ch, CURLOPT_COOKIE, "log1=cookie1;log2=cookie2"); // or like this
i have two sites A and B i would like to be able to have a verified user from site A log on to site B,
Site A - uses php;
Site B - uses Zend Framework.
i would like to have a iframe on site A to the private part of site B or a redirect to Site B
when i do a html post from a form on site A with the credentials i get redirected and logged in everything works, i would like to do it more securely from the server side in php. when i post using php curl the user does not get logged in inside the iframe, i tired redirecting but again the user is not logged in on Site B.
I dont know why html form works and php curl doesn't? am i suppose to send something else using curl, or is a problem with Zend?
----- ok after some more googling i have narrowed the problem down to the cookies i believe i have to set them but i dont know how? is this correct? how would i go about setting them in php? or do i pass on the header where the cookie is set to the browser and forward to site B? if so how do i do this?
here is my code so far.
<?php
$data = array(
'useremail' => 'someemail',
'password' => 'somepassword'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://siteb.com/account/login");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE );
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt"); // Cookie management.
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
?>
<html>
<body>
<iframe src="http://SiteB.com/account/login" width="950" height="700"></iframe>
<form action="http://SiteB.com/account/login" method="post">
email: <input type="text" name="useremail" value="useremail" /><br />
password: <input type="text" name="password" value="somepassword" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
thanks for your time and help.
" when i post using php curl the user does not get logged in inside the iframe, i tired redirecting but again the user is not logged in on Site B."
my ans : Think of Php-Curl as a broswer. And the broswer you are executing the script as a different browser. for the iframe authentication to work, the cookie needs to be set int he browser. When you authenticate from a PHP script , the cookie is set on the PHP-curl broswer. Both of these broswers do not share cookies. I dont think you can make the user login like this.
Are you using a Windows server or a Linux server?
i believe i have to set them but i dont know how? is this correct?
You are doing it right by seeting the curl options to use cookies.
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); // Cookie management.
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
Btw, Can you try the below code and check if the cookies%randNum%.txt is being generated in your cookies folder? Btw create a cookies folder in the same folder as the script before executing. Just to make sure you ahve all the cookies in a folder rather than spread amongst the script files.
<?
$mypath = getcwd();
$mypath = preg_replace('/\\\\/', '/', $mypath);
$rand = rand(1, 15000);
$cookie_file_path = "$mypath/cookies/cookie$rand.txt";
$data = array(
'useremail' => 'someemail',
'password' => 'somepassword'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://siteb.com/account/login");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE );
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); // Cookie management.
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
?>
Did you create cookies.txt and allow the web server's user to write to it?
http://siteb.com/account/login will need to start a session (or write cookies).
cURL will handle the rest.
I am using the Furk.net API and I have managed to successfully login using a curl function and submitting the post data to the proper URL (http://api.furk.net/api/login/login). When I echo the results, I get a success message and the cookie is successfully stored on my server. However, when I try to then retrieve information from the API, it gives me access denied. I'm wondering why my cookie isn't being used for all following requests?
function getUrl($url, $method='', $vars='') {
global $megauser;
$ch = curl_init();
if ($method == 'post') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$buffer = curl_exec($ch);
curl_close($ch);
return $buffer;
}
$login_data = array(
'login' => 'user',
'pwd' => 'pass'
);
echo getUrl('http://api.furk.net/api/login/login','post', $login_data);
If I try another request on the API using this same function while the cookie exists, I get access denied, but if I try the same request in my browser while logged in, I get the appropriate results.
When you login, you don't need to save the cookie. You will receive an answer from the API with the apy_key.
You need to keep that key, and send it along with all your other requests to the API (As as POST parameter)
And you should not use the cookie and the api_key at the same time, as some requests are denied if both are sent.