Cross-Domain Session Sharing PHP - php

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?

Related

Need to share session to LOCAL psuedo server on same domain in PHP through CURL

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);
}

Redirect Curl request with data

I have a PHP curl request which works - However, if i set CURLOPT_FOLLOWLOCATION as 1, the Curl post is submitted with the postdata, the redirected page HTML is captured and posted on my localserver.
The entire redirect is contained within my local server and it doesnt actually transfer me across to the redirection itself with the data (which is what i want). After a few seconds of the html being downloaded on my post.php, it redirects to a page not found.
However, if i set the CURLOPT_FOLLOWLOCATION as 0 and then fetch the correct URL and then redirect it through header("Location: $redirect"); - it transfers fine but there no more data being transferred.
What would be the best way of transferring that data to the new header location.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'postdata=' . urlencode(xmlGrab()));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
// Download the given URL, and return output
$output = curl_exec($ch);
$headers = substr($output, 0, $curl_info["header_size"]); //split out header
$redirect = curl_getinfo($ch)['redirect_url'];
header('HTTP/1.1 307 Temporary Redirect');
header("Location: $redirect");
// Close the cURL resource, and free system resources
curl_close($ch);
Example Scenario:
User Submits a post http://localhost:8888/post.php
Post.php contains a connection to google.co.uk
Post.php connects and makes a post to google.co.uk
The request downloads google.co.uk?q=blahblah to post.php
post.php looks exactly like google.co.uk?q=blahblah
3 seconds later, it redirects to http;//localhost:8888/?q=blahblah
Check the value of $redirect.
If it's a relative url you have to prepend the protocol+hostname+etc to the url, otherwise you'll end up on your local server.

cURL Login on Website

here´s my problem:
I´m trying to get the content of a website that first needs a login. I wanted to solve this via cURL.
First I´m connecting to the Login-Page, than to a page that requires the login.
I get some Cookies in my cookie file back, but when I try to see the content of the page that requires a login before, I only get redirected to (get the content of) the login page.
Seems that parsing my login cookie or whatever fails, so the website don´t remeber that I logged in.
Heres is my php-Code so far:
<?php
$loginUrl = 'https://www.****./login.html';
$loginFields = array('j_username'=>'***', 'j_password'=>'**'); //login form field names and values
$remotePageUrl = 'https://www.***/myPage/index.html'; //url of the page I want the content
$login = getUrl($loginUrl, 'post', $loginFields); //login to the site
echo $remotePage = getUrl($remotePageUrl); //get the remote page
function getUrl($url, $method='', $vars='') {
$ch = curl_init();
if ($method == 'post') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIESESSION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'C:\\xampp\htdocs\***\cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'C:\\xampp\htdocs\****\cookies.txt');
$buffer = curl_exec($ch);
if (curl_error($ch)) echo curl_error($ch);
curl_close($ch);
return $buffer;
}
?>
Any ideas? Searched now for hours in the web, and didn´t find a solution yet.
Thanks!
I did not find any solution. Nevertheless I did all the work manually and don´t need the programm anymore, anyway thanks for the comments :)

CURLOPT_COOKIEFILE doesnt append Cookie header

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));
}
}

using curl and storing cookie as a variable

i have a curl function that visits a website, logs in to said website, stores the cookie file, then can later read the cookie file to visit a page that would normally require a login.
problem i am faced with is i want to save and retrieve the cookie file using a php variable but cant seem to get it to work.
$username = "myusername";
function getUrl($url, $method='', $vars='') {
$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, "cookies/$username.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies/$username.txt");
$buffer = curl_exec($ch);
curl_close($ch);
return $buffer;
}
i assume the syntax is wrong, and not that curl cant handle a variable as a location?
The problem is the scope of the $username variable. Because it's outside the function, it's not available inside the function. You should either add the username as a parameter of the function or use the global keyword so that it's accessible inside the function.
See http://ca2.php.net/manual/en/language.variables.scope.php for more information.

Categories