Edit a Drupal page from another PHP site using cURL
Last modified: February 8, 2009 - 00:47
This is sample code to edit a Drupal page from another PHP site using cURL.
<?php
// ***********************************************
// ********* Login into drupal
// ***********************************************
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://localhost/test/drupal/?q=node&destination=node");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP script');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "name=mylogin&pass=mypass&form_id=user_login_block");
ob_start(); // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean(); // stop preventing output
curl_close ($ch);
unset($ch);
// ***********************************************
// ********** get page create form (necesary for getting token)
// ***********************************************
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_URL,"http://localhost/test/drupal/?q=node/add/page");
$buf3 = curl_exec ($ch);
curl_close ($ch);
// find form token
preg_match('@edit-page-node-form-form-token" *value="([^"]*)"@',$buf3,$matches);
$token=$matches[1];
echo "token:$token\n";
// ***********************************************
// ********* post form, using token
// ***********************************************
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_URL,"http://localhost/test/drupal/?q=node/add/page");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "title=testtitle&body=testbody&status=1&revision=1&op=Submit&form_id=page_node_form&form_token=$token");
$buf2 = curl_exec ($ch);
curl_close ($ch);
?>
1. I got page submitted as
1. I got page submitted as anonymous. I've changed all
cookie.txttod6_cookie.txtand it works properly.2. Make sure php_cURL extension is installed in your PHP environment.
You also need to have the
You also need to have the user login block enabled for the front page on the site your tying to login to. It doesn't work otherwise.
I don't know exactly how to
I don't know exactly how to explain this, but it happened to me that curl fails the login the first time it tries (when there is no cookie file on disk) and succeeds at the subsequent call. The solution to my problem was simply retrying, cycling two times through the
// ********* Login into drupal
part.
my empire of bytes: digitalillusion.altervista.org