WebTechKitchen; Your Web Technology Kitchen, contact us to create, or maintain your websites and other digital properties.

Drupal 7 create a user using rest and curl

Submitted by barnettech on Wed, 05/11/2011 - 16:47
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://base_url/user/login");
curl_setopt($ch, CURLOPT_HEADER, 0);
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=username&pass=password&form_id=user_login");
ob_start();  //dont print out this output 
curl_exec ($ch);

curl_setopt($ch, CURLOPT_URL,"http://base_url/drupal7/test_endpoint/users");
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
//curl_setopt($ch, CURLOPT_HTTPGET, 1);
ob_end_clean();  //resume printout output to screen

/*if ($ret->info['http_code'] == 200) {
      $ret->response = json_decode($ret->response);
    }*/

//print_r($ret);
curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_FAILONERROR, true);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$resourceData = array( 'account' => array('username' => 'jbarnett',   
					  'name' => 'jbarnett', 
                                          'pass' => 'xxxxxx',                 
                                          'mail' => 'barnettjames@yahoo.com',                    
                                         ),
                     ); 

$data2 = http_build_query($resourceData, '', '&');


curl_setopt($ch, CURLOPT_POSTFIELDS, "account=".$data2);

$ret = new stdClass;
$ret->response = curl_exec($ch); // execute and get response
$ret->error    = curl_error($ch);
$ret->info     = curl_getinfo($ch);

/*if ($ret->info['http_code'] == 200) {
      $ret->response = json_decode($ret->response);
    }*/
print $ret->response;
print $ret->error;



curl_close ($ch);
unset($ch);



?>

One thing: it throws away the first element 'username' in this array, hence I just put in a bogus element (I'm still looking at why it's doing this):

$resourceData = array( 'account' => array('username' => 'jbarnett',   
					  'name' => 'jbarnett', 
                                          'pass' => 'xxxxxx',                 
                                          'mail' => 'barnettjames@yahoo.com',                    
                                         ),
                     );