Edit a Drupal page from another PHP site using cURL

This is sample code to edit a Drupal page from another PHP site using cURL.

// ***********************************************
// ********* 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);

 
 

Drupal is a registered trademark of Dries Buytaert.