In some cases it may be desirable to externally access authenticated user paths on our Drupal site. I use this approach to kick off various admin functions.
In order to access authenticated user paths it is necessary to establish a session as shown in the following script.
Usage is simple. Save the script as say remote-login.php in the Drupal root directory along side index.php.
To access our authenticated user path:
wget http://www.drupalsite.com/remote-login.php?user=admin&passwd=admin&path=some/auth/user/path
remote-login.php
<?php
// authenticate
$userName = $_REQUEST["user"];
$password = $_REQUEST["passwd"];
$path = $_REQUEST["path"];
$site = 'http://'.$_SERVER['SERVER_NAME'];
$fail = "REMOTE_LOGIN_FAIL";
$cookiefile=tempnam("/tmp", "cookie");
// get login form.
// can perhaps reduce to one curl_exec
// with mods to curl_setopt
$crl = curl_init();
$url = $site."/user/login";
curl_setopt($crl, CURLOPT_URL, $url);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLOPT_COOKIEJAR, $cookiefile);
$result=curl_exec($crl);
$info = curl_getinfo($crl);
curl_close ($crl);
if ($info['http_code'] != 200) {
unlink($cookiefile);
die("$fail : ".$info['http_code']);
}
// login
$crl = curl_init();
$url = $site."/user/login";
curl_setopt($crl, CURLOPT_URL, $url);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLOPT_COOKIEFILE, $cookiefile);
curl_setopt($crl, CURLOPT_COOKIEJAR, $cookiefile);
curl_setopt($crl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($crl, CURLOPT_POST, 1);
$postdata=array(
"name" => $userName,
"pass" => $password,
"form_id" => "user_login",
"op" => "Log in",
);
curl_setopt ($crl, CURLOPT_POSTFIELDS, $postdata);
$result=curl_exec($crl);
$headers = curl_getinfo($crl);
curl_close ($crl);
// if at same url then login failed.
// we should have been redirected to user's page
if ($headers['url'] == $url) {
unlink($cookiefile);
die("$fail");
}
// call our target path and return output
$url = $site."/$path";
$crl=curl_init();
curl_setopt($crl, CURLOPT_URL, $url);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($crl, CURLOPT_COOKIEFILE, $cookiefile);
$result = curl_exec($crl);
curl_close($crl);
unlink($cookiefile);
echo($result);
?>
Tue, 08/31/2010 - 13:39
Thank you so much for posting this! And also cross posting it on the Drupal documentation site. You save me hours of time.
»
Post new comment