I'm trying to update subscribers automatically to a Mailchimp list. I can update the list using a string from a form etc. However the e-commerce site I'm working on already has an email address stored in the session which I need to use but it's lost when using Curl. Can anyone help?
The example below is using a form which I've included for reference.
<?php
session_start();
if(isset($_POST['submit'])){
$email = $_POST['email'];
if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL) === false){
// MailChimp API credentials
$apiKey = 'xxx-us14';
$listID = 'xxxxxxxx';
// MailChimp API URL
$memberID = md5(strtolower($email));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;
// member information
$json = json_encode([
'email_address' => $email,
'status' => 'subscribed',
'double_optin' => false,
'send_welcome' => true,
'update_existing' => false,
'replace_interests' => false,
'merge_fields' => [
'FNAME' => $fname,
'LNAME' => $lname
]
]);
// send a HTTP POST request with curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
If you are wanting to pull data out of your session you will need to use the PHP $_SESSION
superglobal. The code above looks to be using the $_POST
superglobal and accessing its email
value. $_SESSION
Documented here: http://php.net/manual/en/reserved.variables.session.php
I do want to mention that its traditionally not a safe practice to send data read directly from your session in an over the wire request. If this is a form I would suggest making use of the $_POST you are already sending. If you don't want your user to have to input their email address you could use a pre-populated hidden field on your form.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.