user1486133
user1486133

Reputation: 1457

using cURL with PHP for POST request

Sorry if this is really vague, I'm new to both cURL and interacting with API's.

Currently I have created a URL with the authentication details required that will access the API (dotmailer) and display the contacts in the address book with the given ID.

$auth_url = 'https://' . $apiemail .':' . $apipassword . '@api.dotmailer.com/v2/address-books/' . $listID .'/contacts';

Which sends me somewhere a little like this:

https://username:[email protected]/v2/address-books/listID/contacts

Here is the XML from that page

<ApiContact>
<Id>1058905201</Id>
<Email>[email protected]</Email>
<OptInType>Unknown</OptInType>
<EmailType>Html</EmailType>
<DataFields i:nil="true"/>
<Status>Subscribed</Status>
</ApiContact>
</ArrayOfApiContact>

Now I need to POST a variable to the API. My variable is $useremail

I was planning to use cURL to do this a I'm using PHP and avoiding SOAP instead using REST.

I'm completely new to this but I had a go with some code that doesn't work, but hey I tried!

// Authenticate
$auth_url = 'https://' . $apiemail .':' . $apipassword . '@api.dotmailer.com/v2/address-books/' . $listID .'/contacts';

// open connection
$ch = curl_init();

// set the URL
curl_setopt($ch,CURLOPT_URL, $auth_url);
curl_setopt($ch,CURLOPT_POST, $useremail);

// execute post
$result = curl_exec($ch);

// close connection
curl_close($ch);

I know this is way off but:

Sorry if this is vague. I appreciate anyone's advice.

Upvotes: 0

Views: 583

Answers (1)

Artur Kedzior
Artur Kedzior

Reputation: 4263

First of all, if you launch this url in the browser:

https://username:[email protected]/v2/address-books/listID/contacts

does it work for you?

If so, echo the $auth_url.

$auth_url = 'https://' . $apiemail .':' . $apipassword . '@api.dotmailer.com/v2/address-books/' . $listID .'/contacts';
echo $auth_url;

and check if your url is constructed correctly. Then:

EDIT

$data = array("Email" => "[email protected]");                                                                    
$data_string = json_encode($data); 
$req = curl_init($auth_url);
curl_setopt($req, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($req, CURLOPT_POST, 1);
curl_setopt($req, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($req, CURLOPT_HTTPHEADER, array(                                                                          
'Content-Type: application/json',                                                                                
'Content-Length: ' . strlen($data_string))                                                                       
); 
$res = curl_exec($req);
curl_close($req);

Upvotes: 1

Related Questions