php - Using cURL to POST form to two places

697

Yesterday I asked a question about how I could go about hijacking my MailChimp contact form to send an additional email (when certain conditions are met).

I wrote changed theaction="... from the MailChimp URL to my ownprocess_email.php with code resembling the following:

extract($_POST);
$url = 'http://myMailchimpUser.us2.list-manage.com/subscribe/post';
$fields = array(
    'u' => urlencode($u),
    'id' => urlencode($id),
    'group' => http_build_query ($group),
    'MERGE1' => urlencode($MERGE1),
    'MERGE2' => urlencode($MERGE2),
    'MERGE3' => http_build_query($MERGE3),
    'other_more_info_text' => urlencode($other_more_info_text),
    'submit' => urlencode($submit)
);

foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

$result = curl_exec($ch);
curl_close($ch);

I have yet to add the code which sends the email to myself, but that should be trivial. The problem I'm having with this code is that instead of redirecting me to the MailChimp page, its actually loading withinprocess_email.php (and its loading incorrectly to boot.)

I know I can accomplish what I want to do if I used JavaScript, but it seems to me that isn't the proper way to go about this. Can anyone offer me any help?

984

Answer

Solution:

If I understand correctly: you want to POST data locally first then let the form POST to Mailchimp. If that is what you are trying to do, then using some JS connected to the form (or a form button) is probably the best way to go. I think it is the proper way to go in your situation.

Something jQuery like below would work to POST the form locally first, and once that request is complete it would submit the form using the given action url (mailchimp).

$(document).ready(function(){
    $('#submit-button').click(function(event){
        event.preventDefault();
        $.post("your_email_parser.php", $('#form-id').serialize(), function(){
            $('#form-id').submit();
        });
    });
});

...

<form id='form-id' action='http://myMailchimpUser.us2.list-manage.com/subscribe/post' method='post'>
    ...
    <input type='submit' id='submit-button' />
</form>

People are also looking for solutions to the problem: echo php tags in php

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.