using PHP to add subscribers

Im using this form from a template to collect email addresses for a list in campaign monitor.

the html:

          <form id="subform" method="post">
            <fieldset>
              <p>
                <input name="name" onfocus="if (this.value == 'Name') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Name';}" value="Name"/>
              </p>
              <p>
                <input name="email" onfocus="if (this.value == 'Email') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Email';}" value="Email"  class="required email" />
              </p>
              <p>
                <input class="sub_submit" type="submit" value="Continue registering"/>
              </p>
            </fieldset>
          </form>

interpreted by a custom.js file:

//subscribe form
$(function(){
    $('#subform').validate({
        submitHandler: function(form) {
                $(form).ajaxSubmit({
                    url: 'http://wordsoflife.com/wohp/php/subscribe-form.php',
                    clearForm: true,
                    success: function() {
                        $('.sub_inner').hide();
                        $('.subscribe').append("<h3>Thank you!</h3><p>You have Successfuly registered to attend the Word Of His Power Conference! <br><br>You have been subscribed to receive email updates and news about Word of His Power! <br><br> See you there!</p>")
                    }
                });
            }
    });         
});

Which goes to this PHP Document:

<?php

$name=$_POST['name'];
$email=$_POST['email'];


$to='samisthesound@me.com';

$headers = 'From: '.$email."\r\n" .
    'Reply-To: '.$email."\r\n" .
    'X-Mailer: PHP/' . phpversion();
    
$subject = 'Registration';
$body='You have got a new registration request for WOHP'."\n\n";

$body.='Name: '.$name."\n";
$body.='Email: '.$email."\n";

    
if(mail($to, $subject, $body, $headers)) {
    die('Registration complete');
} else {
    die('Error: Mail failed');
}

?>

Which successfully generates an email to me. However I don't want an email, I want it to automatically go to Campaign Monitor.

So, my problem is that I don't understand PHP enough to know how to use the POST method to send the info that has been collected to Campaign Monitor.

I know this is super easy. Can someone help me out?

Thank you!

benz, 4 years ago

Hi Sam,

The easiest way is first download the PHP wrapper (http://www.campaignmonitor.com/api/samples-and-wrappers/).
In that wrapper there's a bunch of classes and a series of examples, have a look at samples/subscribers/add.php.

You can pretty much splice that into your existing code - using the wrapper and the subscriber object it provides it really only takes a couple of lines to do - you've done the hard bit already!

samgualtieri, 4 years ago

Hey benz, thanks for the response.

The thing is, I don't understand the API Documentation because I'm so new to PHP.

I was kind of hoping someone could give me a crash course in syntax and what lines I need.

Phil Phil, 4 years ago

Hi sam,

Benz's advice is very good. You should start by making sure you have your api key and the required listID for the list you want to subscribe people to. You'll need those for modifying the php script.

There is an example available as part of the php wrapper which can easily be modified to include the form processing code that you need to keep. For example, you could do something like what follows. I've inserted a few extra lines and put some comments in to explain what's going on:

<?php
// this includes the necessary wrapper classes
// make sure you adjust the path so that it's correct for your application file structure
require_once '../../csrest_subscribers.php';

// get the name and email from the form
$name=$_POST['name'];
$email=$_POST['email'];

// this stuff makes the API call
// replace 'Your list ID' and 'Your API key' with the values for your account
// once you've checked out the getting started link
$wrap = new CS_REST_Subscribers('Your list ID', 'Your API Key');
$result = $wrap->add(array(
    'EmailAddress' => $email,
    'Name' => $name,
    'CustomFields' => array(), // no custom fields, can remove this line completely
    'Resubscribe' => true
));

// this is all being ignored by your javascript file anyway
// but i'll leave it in for completeness
echo "Result of POST /api/v3/subscribers/{list id}.{format}\n<br />";
if($result->was_successful()) {
    echo "Subscribed with code ".$result->http_status_code;
} else {
    echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
    var_dump($result->response);
    echo '</pre>';
}
?>

In terms of figuring out the syntax etc, there's no substitute for just playing around with it and just trying it out.

Good luck!

samgualtieri, 4 years ago

Thank you Phil!

I've tried several things, but none of them have worked yet. I'm learning a bit though! Here's what my code looks like now:

<?php

require_once '/csrest_subscribers.php';

$name=$_POST['name'];
$email=$_POST['email'];


$wrap = new CS_REST_Subscribers('DELETED', 'DELETED');
$result = $wrap->add(array(
    'EmailAddress' => '$email',
    'Name' => '$name',
    'Resubscribe' => true
));


?>

I have the csrest_subscribers.php file on the server in the same folder as this .php doc.

Am I supposed to upload the whole wrapper folder to the server as well? I did just to be safe...

Am I close?

Phil Phil, 4 years ago

Hi Sam,

Firstly, i've removed your apiKey and listID from the code sample above. Those are private keys and shouldn't be placed anywhere on a public forum.

Whether you're close or not is hard to tell, but unfortunately i don't think so :( If you have a look at the code for csrest_subscribers.php you'll see it depends on the base_classes.php file, which in turn depends on others in the wrapper. In order for all of that to operate seemlessly you'll need to make sure the entire wrapper folder (apart from the samples) is on the server, with the folder structure completely preserved. If you go moving files around,the php interpreter won't be able to find them.

You're a beginner and don't know how to go about debugging your own code, so my advice is this: start with the samples. Make the minimum modifications necessary (replacing apiKey, listID, subscriber data etc) to get the samples working (by calling the php file directly in the browser). The good thing about using the samples is that they'll output error codes in your browser that might help you to figure out where you're going wrong.

Once you've got the samples working, you can start to make small changes to bring it more in line with what you're needing, according to what we discussed earlier. Test after each small change. Small changes are good because it means you can immediately identify when you've done something wrong and can go about fixing that.

Beyond that, it's going to impossible to help you from here. Wish i could do more, but you'll need to get someone who knows php or programming in general to sit with you and help you through the process.

Good luck with it :)

meenie, 1 year ago

Its worth mentioning that things have changed a little since the posts above.

Your best bet is check out the samples in the wrappers

Join 200,000 companies around the world that use Campaign Monitor to run email marketing campaigns that deliver results for their business.

Get started for free
1-888-533-8098