I have integrated mailchimp with my php website for subscription, Its working but the issue is when same user re-enter his details it still says "Thanks you are added to mailing list" instead of saying "You are already subscribed".
Tried a lot but then either my button stop working or the code stop working..
HTML Code:
<form id="signup" class="formee" action="php/subscribe.php" method="post">
<div class="form-group has-feedback">
<label>First Name</label>
<div class="clearfix"></div>
<input type="text" id="fname" name="fname" >
<label>Last Name</label>
<div class="clearfix"></div>
<input type="text" id="lname" name="lname">
<label>Email Address</label>
<div class="clearfix"></div>
<input type="text" id="email" name="email">
<div class="newsletter-submit">
<button class="btn btn_newslatter right inputnew" type="submit" title="Submit" value="Send" >Submit</button>
</div>
<div id="response"></div>
</div>
</form>
JS:
<script type="text/javascript">
$(document).ready(function(a){
// jQuery Validation
$("#signup").validate({
// if valid, post data via AJAX
submitHandler: function(form) {
$.post("php/subscribe.php", { fname: $("#fname").val(), lname: $("#lname").val(), email: $("#email").val() }, function(data) {
$('#response').html(data);
});
},
// all fields are required
rules: {
fname: {
required: false
},
lname: {
required: false
},
email: {
required: true,
email: true
}
}
});
PHP (subscribe.php):
<?php
require_once 'MCAPI.class.php';
$api = new MCAPI('xxxxxxxxxxxx');
$merge_vars = array('FNAME'=>$_POST["fname"], 'LNAME'=>$_POST["lname"]);
// Submit subscriber data to MailChimp
// For parameters doc, refer to: http://apidocs.mailchimp.com/api/1.3/listsubscribe.func.php
$retval = $api->listSubscribe( 'xxxxxxx', $_POST["email"], $merge_vars, 'html', false, true );
if ($api->errorCode){
echo "<h4>Please try again.</h4>";
} else {
echo "<h4>Thank you, you have been added to our mailing list.</h4>";
}
// store the status message based on response code
if ($httpCode == 200) {
$_SESSION['msg'] = '<p style="color: #34A853">You have successfully subscribed to CodexWorld.</p>';
} else {
switch ($httpCode) {
case 214:
$msg = 'You are already subscribed.';
break;
default:
$msg = 'Some problem occurred, please try again.';
break;
}
$_SESSION['msg'] = '<p style="color: #EA4335">'.$msg.'</p>';
}
?>
MCAPI.class.php:
<?php
class MCAPI {
var $version = "1.3";
var $errorMessage;
var $errorCode;
/**
* Cache the information on the API location on the server
*/
var $apiUrl;
/**
* Default to a 300 second timeout on server calls
*/
var $timeout = 300;
/**
* Default to a 8K chunk size
*/
var $chunkSize = 8192;
/**
* Cache the user api_key so we only have to log in once per client instantiation
*/
var $api_key;
/**
* Cache the user api_key so we only have to log in once per client instantiation
*/
var $secure = false;
/**
* Connect to the MailChimp API for a given list.
*
* #param string $apikey Your MailChimp apikey
* #param string $secure Whether or not this should use a secure connection
*/
function MCAPI($apikey, $secure=false) {
$this->secure = $secure;
$this->apiUrl = parse_url("http://api.mailchimp.com/" . $this->version . "/?output=php");
$this->api_key = $apikey;
}
function setTimeout($seconds){
if (is_int($seconds)){
$this->timeout = $seconds;
return true;
}
}
function getTimeout(){
return $this->timeout;
}
function useSecure($val){
if ($val===true){
$this->secure = true;
} else {
$this->secure = false;
}
}
/**
* Actually connect to the server and call the requested methods, parsing the result
* You should never have to call this function manually
*/
function __call($method, $params) {
$dc = "us1";
if (strstr($this->api_key,"-")){
list($key, $dc) = explode("-",$this->api_key,2);
if (!$dc) $dc = "us1";
}
$host = $dc.".".$this->apiUrl["host"];
$this->errorMessage = "";
$this->errorCode = "";
$sep_changed = false;
//sigh, apparently some distribs change this to & by default
if (ini_get("arg_separator.output")!="&"){
$sep_changed = true;
$orig_sep = ini_get("arg_separator.output");
ini_set("arg_separator.output", "&");
}
//mutate params
$mutate = array();
$mutate["apikey"] = $this->api_key;
foreach($params as $k=>$v){
$mutate[$this->function_map[$method][$k]] = $v;
}
$post_vars = http_build_query($mutate);
if ($sep_changed){
ini_set("arg_separator.output", $orig_sep);
}
$payload = "POST " . $this->apiUrl["path"] . "?" . $this->apiUrl["query"] . "&method=" . $method . " HTTP/1.0\r\n";
$payload .= "Host: " . $host . "\r\n";
$payload .= "User-Agent: MCAPImini/" . $this->version ."\r\n";
$payload .= "Content-type: application/x-www-form-urlencoded\r\n";
$payload .= "Content-length: " . strlen($post_vars) . "\r\n";
$payload .= "Connection: close \r\n\r\n";
$payload .= $post_vars;
ob_start();
if ($this->secure){
$sock = fsockopen("ssl://".$host, 443, $errno, $errstr, 30);
} else {
$sock = fsockopen($host, 80, $errno, $errstr, 30);
}
if(!$sock) {
$this->errorMessage = "Could not connect (ERR $errno: $errstr)";
$this->errorCode = "-99";
ob_end_clean();
return false;
}
$response = "";
fwrite($sock, $payload);
stream_set_timeout($sock, $this->timeout);
$info = stream_get_meta_data($sock);
while ((!feof($sock)) && (!$info["timed_out"])) {
$response .= fread($sock, $this->chunkSize);
$info = stream_get_meta_data($sock);
}
fclose($sock);
ob_end_clean();
if ($info["timed_out"]) {
$this->errorMessage = "Could not read response (timed out)";
$this->errorCode = -98;
return false;
}
list($headers, $response) = explode("\r\n\r\n", $response, 2);
$headers = explode("\r\n", $headers);
$errored = false;
foreach($headers as $h){
if (substr($h,0,26)==="X-MailChimp-API-Error-Code"){
$errored = true;
$error_code = trim(substr($h,27));
break;
}
}
if(ini_get("magic_quotes_runtime")) $response = stripslashes($response);
$serial = unserialize($response);
if($response && $serial === false) {
$response = array("error" => "Bad Response. Got This: " . $response, "code" => "-99");
} else {
$response = $serial;
}
if($errored && is_array($response) && isset($response["error"])) {
$this->errorMessage = $response["error"];
$this->errorCode = $response["code"];
return false;
} elseif($errored){
$this->errorMessage = "No error message was found";
$this->errorCode = $error_code;
return false;
}
return $response;
}
protected $function_map = array('campaignUnschedule'=>array("cid"),
'campaignSchedule'=>array("cid","schedule_time","schedule_time_b"),
'campaignScheduleBatch'=>array("cid","schedule_time","num_batches","stagger_mins"),
'campaignResume'=>array("cid"),
'campaignPause'=>array("cid"),
'campaignSendNow'=>array("cid"),
'campaignSendTest'=>array("cid","test_emails","send_type"),
'campaignSegmentTest'=>array("list_id","options"),
'campaignCreate'=>array("type","options","content","segment_opts","type_opts"),
'campaignUpdate'=>array("cid","name","value"),
'campaignReplicate'=>array("cid"),
'campaignDelete'=>array("cid"),
'campaigns'=>array("filters","start","limit","sort_field","sort_dir"),
'campaignStats'=>array("cid"),
'campaignClickStats'=>array("cid"),
'campaignEmailDomainPerformance'=>array("cid"),
'campaignMembers'=>array("cid","status","start","limit"),
'campaignHardBounces'=>array("cid","start","limit"),
'campaignSoftBounces'=>array("cid","start","limit"),
'campaignUnsubscribes'=>array("cid","start","limit"),
'campaignAbuseReports'=>array("cid","since","start","limit"),
'campaignAdvice'=>array("cid"),
'campaignAnalytics'=>array("cid"),
'campaignGeoOpens'=>array("cid"),
'campaignGeoOpensForCountry'=>array("cid","code"),
'campaignEepUrlStats'=>array("cid"),
'campaignBounceMessage'=>array("cid","email"),
'campaignBounceMessages'=>array("cid","start","limit","since"),
'campaignEcommOrders'=>array("cid","start","limit","since"),
'campaignShareReport'=>array("cid","opts"),
'campaignContent'=>array("cid","for_archive"),
'campaignTemplateContent'=>array("cid"),
'campaignOpenedAIM'=>array("cid","start","limit"),
'campaignNotOpenedAIM'=>array("cid","start","limit"),
'campaignClickDetailAIM'=>array("cid","url","start","limit"),
'campaignEmailStatsAIM'=>array("cid","email_address"),
'campaignEmailStatsAIMAll'=>array("cid","start","limit"),
'campaignEcommOrderAdd'=>array("order"),
'lists'=>array("filters","start","limit","sort_field","sort_dir"),
'listMergeVars'=>array("id"),
'listMergeVarAdd'=>array("id","tag","name","options"),
'listMergeVarUpdate'=>array("id","tag","options"),
'listMergeVarDel'=>array("id","tag"),
'listMergeVarReset'=>array("id","tag"),
'listInterestGroupings'=>array("id"),
'listInterestGroupAdd'=>array("id","group_name","grouping_id"),
'listInterestGroupDel'=>array("id","group_name","grouping_id"),
'listInterestGroupUpdate'=>array("id","old_name","new_name","grouping_id"),
'listInterestGroupingAdd'=>array("id","name","type","groups"),
'listInterestGroupingUpdate'=>array("grouping_id","name","value"),
'listInterestGroupingDel'=>array("grouping_id"),
'listWebhooks'=>array("id"),
'listWebhookAdd'=>array("id","url","actions","sources"),
'listWebhookDel'=>array("id","url"),
'listStaticSegments'=>array("id"),
'listStaticSegmentAdd'=>array("id","name"),
'listStaticSegmentReset'=>array("id","seg_id"),
'listStaticSegmentDel'=>array("id","seg_id"),
'listStaticSegmentMembersAdd'=>array("id","seg_id","batch"),
'listStaticSegmentMembersDel'=>array("id","seg_id","batch"),
'listSubscribe'=>array("id","email_address","merge_vars","email_type","double_optin","update_existing","replace_interests","send_welcome"),
'listUnsubscribe'=>array("id","email_address","delete_member","send_goodbye","send_notify"),
'listUpdateMember'=>array("id","email_address","merge_vars","email_type","replace_interests"),
'listBatchSubscribe'=>array("id","batch","double_optin","update_existing","replace_interests"),
'listBatchUnsubscribe'=>array("id","emails","delete_member","send_goodbye","send_notify"),
'listMembers'=>array("id","status","since","start","limit","sort_dir"),
'listMemberInfo'=>array("id","email_address"),
'listMemberActivity'=>array("id","email_address"),
'listAbuseReports'=>array("id","start","limit","since"),
'listGrowthHistory'=>array("id"),
'listActivity'=>array("id"),
'listLocations'=>array("id"),
'listClients'=>array("id"),
'templates'=>array("types","category","inactives"),
'templateInfo'=>array("tid","type"),
'templateAdd'=>array("name","html"),
'templateUpdate'=>array("id","values"),
'templateDel'=>array("id"),
'templateUndel'=>array("id"),
'getAccountDetails'=>array("exclude"),
'getVerifiedDomains'=>array(),
'generateText'=>array("type","content"),
'inlineCss'=>array("html","strip_css"),
'folders'=>array("type"),
'folderAdd'=>array("name","type"),
'folderUpdate'=>array("fid","name","type"),
'folderDel'=>array("fid","type"),
'ecommOrders'=>array("start","limit","since"),
'ecommOrderAdd'=>array("order"),
'ecommOrderDel'=>array("store_id","order_id"),
'listsForEmail'=>array("email_address"),
'campaignsForEmail'=>array("email_address","options"),
'chimpChatter'=>array(),
'searchMembers'=>array("query","id","offset"),
'searchCampaigns'=>array("query","offset","snip_start","snip_end"),
'apikeys'=>array("username","password","expired"),
'apikeyAdd'=>array("username","password"),
'apikeyExpire'=>array("username","password"),
'ping'=>array(),
'deviceRegister'=>array("mobile_key","details"),
'deviceUnregister'=>array("mobile_key","device_id"),
'gmonkeyAdd'=>array("id","email_address"),
'gmonkeyDel'=>array("id","email_address"),
'gmonkeyMembers'=>array(),
'gmonkeyActivity'=>array());
}
?>
This is the API from 2.0. it does all sorts of bad things in the new API.
I suggest this tutorial: [Misha Rudrastyh - Mailchimp using AJAX and PHP[(https://rudrastyh.com/api/mailchimp-subscription.html)
Just integrated Google Recaptcha. I am using this form as a POST to a secure checkout for a secure transaction site ( API ).
My challenge is, I have the form action =
"action="https://securepayments.cardconnect.com/hpp/payment/"
And event if I use :
if (isset($_POST['submit'])) {
to validate the :: recaptcha :: it still just goes straight to the form action URL without verifying the recaptcha.
Here is more code:
$secret = '-- XX --';
$response = $_POST['g-recaptcha-response'];
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip");
$res = json_decode($unpass, TRUE);
$result = json_decode($url, TRUE);
if ($result['success'] == 1) {
echo $_POST['name'];
echo $_POST['companyname'];
}
else { echo 'you are a robot'; }
}
The form action URL passes POST / hidden variables to connect via MID/Password to authenticate itself with the API. I can't figure out how to integrate a solution to use recaptcha and then do the form action. Any help would be awesome!
function isValid()
{
try {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => 'secret',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return json_decode($result)->success;
}
catch (Exception $e) {
return null;
}
}
if($_POST && isValid())
{
//do stuff
}
Why you don't use the Recaptcha Library?
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Recaptcha
{
/*
* This is a PHP library that handles calling reCAPTCHA.
* - Documentation and latest version
* http://recaptcha.net/plugins/php/
* - Get a reCAPTCHA API Key
* https://www.google.com/recaptcha/admin/create
* - Discussion group
* http://groups.google.com/group/recaptcha
*
* Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
* AUTHORS:
* Mike Crawford
* Ben Maurer
*
* CONTRIBUTION:
* Codeigniter version - 23.08.2012 by Christer Nordbø, Norway.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*
* UPDATE HISTORY:
* 28.08.2013 - Made recaptcha_check_answer() function bit simpler on default
* fields as html is generated by recaptcha_get_html() function.
* Updated by - Puneet Kalra (https://github.com/puneetkay)
*/
/**
* The reCAPTCHA server URL's
*/
const RECAPTCHA_API_SERVER = "http://www.google.com/recaptcha/api";
const RECAPTCHA_API_SECURE_SERVER = "https://www.google.com/recaptcha/api";
const RECAPTCHA_VERIFY_SERVER = "www.google.com";
protected $is_valid;
protected $error;
//Remember to obtain the Public and Private key # https://www.google.com/recaptcha/admin/create
protected $public_key = "YOUR PUBLIC KEY";
protected $privkey = "YOUR PRIVATE KEY";
protected $options = array();
function __construct()
{
log_message('debug', "RECAPTCHA Class Initialized.");
$this->_ci =& get_instance();
//Load the CI Config file for recaptcha
$this->_ci->load->config('recaptcha');
//load in the values from the config file.
$this->public_key = $this->_ci->config->item('public_key');
$this->privkey = $this->_ci->config->item('private_key');
$this->options = $this->_ci->config->item('recaptcha_options');
//Lets do some basic error handling to see if the configuration is A-OK.
$temp_error_msg = '';
if ($this->public_key === 'YOUR PUBLIC KEY') {
$temp_error_msg .= 'You need to set your public key in the config file <br />';
}
if ($this->privkey === 'YOUR PRIVATE KEY') {
$temp_error_msg .= 'You need to set your private key in the config file <br />';
}
if ($temp_error_msg != '') {
show_error($temp_error_msg);
}
}
/**
* Encodes the given data into a query string format
* #param $data - array of string elements to be encoded
* #return string - encoded request
*/
function recaptcha_qsencode($data)
{
$req = "";
foreach ($data as $key => $value)
$req .= $key . '=' . urlencode(stripslashes($value)) . '&';
// Cut the last '&'
$req = substr($req, 0, strlen($req) - 1);
return $req;
}
/**
* Submits an HTTP POST to a reCAPTCHA server
* #param string $host
* #param string $path
* #param array $data
* #param int port
* #return array response
*/
function recaptcha_http_post($host, $path, $data, $port = 80)
{
$req = $this->recaptcha_qsencode($data);
$http_request = "POST $path HTTP/1.0\r\n";
$http_request .= "Host: $host\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
$http_request .= "Content-Length: " . strlen($req) . "\r\n";
$http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
$http_request .= "\r\n";
$http_request .= $req;
$response = '';
if (false == ($fs = #fsockopen($host, $port, $errno, $errstr, 10))) {
die ('Could not open socket');
}
fwrite($fs, $http_request);
while (!feof($fs))
$response .= fgets($fs, 1160); // One TCP-IP packet
fclose($fs);
$response = explode("\r\n\r\n", $response, 2);
return $response;
}
function recaptcha_get_html($error = null, $use_ssl = false)
{
if ($this->public_key == null || $this->public_key == '') {
die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
}
if ($use_ssl) {
$server = self::RECAPTCHA_API_SECURE_SERVER;
} else {
$server = self::RECAPTCHA_API_SERVER;
}
$errorpart = "";
if ($error) {
$errorpart = "&error=" . $error;
}
$options = "";
foreach ($this->options as $key => $value) {
$options .= $key . ':"' . $value . '", ';
}
return '<script type="text/javascript"> var RecaptchaOptions = { ' . $options . ' }; </script>
<script type="text/javascript" src="' . $server . '/challenge?k=' . $this->public_key . $errorpart . '"></script>
<noscript>
<iframe src="' . $server . '/noscript?k=' . $this->public_key . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript>';
}
/**
* Calls an HTTP POST function to verify if the user's guess was correct
* #param string $remoteip
* #param string $challenge
* #param string $response
* #param array $extra_params an array of extra variables to post to the server
* #return ReCaptchaResponse
*/
function recaptcha_check_answer($remoteip = null, $challenge = null, $response = null, $extra_params = array())
{
if ($this->privkey == null || $this->privkey == '') {
die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
}
$remoteip = ($remoteip == null) ? $_SERVER['REMOTE_ADDR'] : $remoteip;
$challenge = ($challenge == null) ? $this->_ci->input->post('recaptcha_challenge_field') : $challenge;
$response = ($response == null) ? $this->_ci->input->post('recaptcha_response_field') : $response;
if ($remoteip == null || $remoteip == '') {
die ("For security reasons, you must pass the remote ip to reCAPTCHA");
}
//discard spam submissions
if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
$this->is_valid = false;
$this->error = 'incorrect-captcha-sol';
}
$response = $this->recaptcha_http_post(self::RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify",
array(
'privatekey' => $this->privkey,
'remoteip' => $remoteip,
'challenge' => $challenge,
'response' => $response
) + $extra_params
);
$answers = explode("\n", $response [1]);
if (trim($answers [0]) == 'true') {
$this->is_valid = true;
} else {
$this->is_valid = false;
$this->error = $answers [1];
}
}
/**
* gets a URL where the user can sign up for reCAPTCHA. If your application
* has a configuration page where you enter a key, you should provide a link
* using this function.
* #param string $domain The domain where the page is hosted
* #param string $appname The name of your application
*/
function recaptcha_get_signup_url($domain = null, $appname = 'Codeigniter')
{
return "https://www.google.com/recaptcha/admin/create?" . $this->recaptcha_qsencode(array('domains' => $domain, 'app' => $appname));
}
function recaptcha_aes_pad($val)
{
$block_size = 16;
$numpad = $block_size - (strlen($val) % $block_size);
return str_pad($val, strlen($val) + $numpad, chr($numpad));
}
/* Mailhide related code */
function recaptcha_aes_encrypt($val, $ky)
{
if (!function_exists("mcrypt_encrypt")) {
die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
}
$mode = MCRYPT_MODE_CBC;
$enc = MCRYPT_RIJNDAEL_128;
$val = $this->recaptcha_aes_pad($val);
return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
}
function recaptcha_mailhide_urlbase64($x)
{
return strtr(base64_encode($x), '+/', '-_');
}
/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
function recaptcha_mailhide_url($email)
{
if ($this->public_key == '' || $this->public_key == null || $this->privkey == "" || $this->privkey == null) {
die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
"you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");
}
$ky = pack('H*', $this->privkey);
$cryptmail = $this->recaptcha_aes_encrypt($email, $ky);
return "http://www.google.com/recaptcha/mailhide/d?k=" . $this->public_key . "&c=" . $this->recaptcha_mailhide_urlbase64($cryptmail);
}
/**
* gets the parts of the email to expose to the user.
* eg, given johndoe#example,com return ["john", "example.com"].
* the email is then displayed as john...#example.com
*/
function recaptcha_mailhide_email_parts($email)
{
$arr = preg_split("/#/", $email);
if (strlen($arr[0]) <= 4) {
$arr[0] = substr($arr[0], 0, 1);
} else if (strlen($arr[0]) <= 6) {
$arr[0] = substr($arr[0], 0, 3);
} else {
$arr[0] = substr($arr[0], 0, 4);
}
return $arr;
}
/**
* Gets html to display an email address given a public an private key.
* to get a key, go to:
*
* http://www.google.com/recaptcha/mailhide/apikey
*/
function recaptcha_mailhide_html($email)
{
$emailparts = $this->recaptcha_mailhide_email_parts($email);
$url = $this->recaptcha_mailhide_url($this->public_key, $this->privkey, $email);
return htmlentities($emailparts[0]) . "<a href='" . htmlentities($url) .
"' onclick=\"window.open('" . htmlentities($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>#" . htmlentities($emailparts [1]);
}
function checkIfIsValid()
{
if ($this->getIsValid()) {
return $this->getIsValid();
} else {
return array($this->getIsValid(), $this->getError());
}
}
function getIsValid()
{
return $this->is_valid;
}
function getError()
{
return $this->error;
}
}
Use it:
$this->load->library('recaptcha');
$this->recaptcha->recaptcha_check_answer();
if (!$this->recaptcha->getIsValid()) {
$this->session->set_flashdata('error', 'Código Captcha incorrecto');
redirect(base_url() . 'add');
}
unset($post['recaptcha_challenge_field']);
unset($post['recaptcha_response_field']);
I'm trying to create a simple contact form in HTML with PHP script for my website. Internet is full of examples, but they usually are too simple or too complicated.
Here's my form in HTML and I need PHP script for it.
<form action="send.php" method="POST" id="form">
<label for="latitude">Lat. °N:</label>
<input id="latitude" name="latitude" type="text" />
<label for="longitude">Long. °E:</label>
<input id="longitude" name="longitude" type="text" />
<label for="desc">Description:</label>
<textarea style="resize:none" name="desc" cols="45" rows="5"></textarea>
<label for="mail">E-mail:</label>
<input type="text" name="mail" /><br>
<input type="submit" name="submit" value="Send">
</form>
It should contain charset=utf-8 to display all of my language's diacritics in a message.
It should have a validation if ALL fields are not empty. E-mail validation is not needed.
It should inform in a very simple way Message send! or Error, try again.
#EWit is right... You can't really use Stack Overflow like this. However, the PHP below should work. Try and pull it apart so you can learn from it. Cheers
<?PHP
define('kOptional', true);
define('kMandatory', false);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('track_errors', true);
function DoStripSlashes($fieldValue) {
if ( function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() ) {
if (is_array($fieldValue) ) {
return array_map('DoStripSlashes', $fieldValue);
} else {
return trim(stripslashes($fieldValue));
}
} else {
return $fieldValue;
}
}
function FilterCChars($theString) {
return preg_replace('/[\x00-\x1F]/', '', $theString);
}
function CheckEmail($email, $optional) {
if ( (strlen($email) == 0) && ($optional === kOptional) ) {
return true;
} elseif ( preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+#((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $email) == 1 ) {
return true;
} else {
return false;
}
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$clientIP = $_SERVER['REMOTE_ADDR'];
}
$FTGlatitude = DoStripSlashes( $_POST['latitude'] );
$FTGlongitude = DoStripSlashes( $_POST['longitude'] );
$FTGdesc = DoStripSlashes( $_POST['desc'] );
$FTGmail = DoStripSlashes( $_POST['mail'] );
$FTGsubmit = DoStripSlashes( $_POST['submit'] );
$validationFailed = false;
if (!CheckEmail($FTGmail, kMandatory)) {
$FTGErrorMessage['mail'] = 'Please enter a valid email address';
$validationFailed = true;
}
if ($validationFailed === true) {
$errorPage = '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>Error</title></head><body>Errors found: <!--VALIDATIONERROR--></body></html>';
$errorPage = str_replace('<!--FIELDVALUE:latitude-->', $FTGlatitude, $errorPage);
$errorPage = str_replace('<!--FIELDVALUE:longitude-->', $FTGlongitude, $errorPage);
$errorPage = str_replace('<!--FIELDVALUE:desc-->', $FTGdesc, $errorPage);
$errorPage = str_replace('<!--FIELDVALUE:mail-->', $FTGmail, $errorPage);
$errorPage = str_replace('<!--FIELDVALUE:submit-->', $FTGsubmit, $errorPage);
$errorPage = str_replace('<!--ERRORMSG:mail-->', $FTGErrorMessage['mail'], $errorPage);
$errorList = #implode("<br />\n", $FTGErrorMessage);
$errorPage = str_replace('<!--VALIDATIONERROR-->', $errorList, $errorPage);
echo $errorPage;
}
if ( $validationFailed === false ) {
$emailSubject = FilterCChars("Website Contact");
$emailBody = chunk_split( base64_encode( "<html>\n"
. "<head>\n"
. "<title></title>\n"
. "</head>\n"
. "<body>\n"
. "Latitude : $FTGlatitude<br />\n"
. "Longitude : $FTGlongitude<br />\n"
. "Desc : " . nl2br( $FTGdesc ) . "<br />\n"
. "Mail : $FTGmail<br />\n"
. "Submit : $FTGsubmit<br />\n"
. "</body>\n"
. "</html>\n"
. "" ) )
. "\n";
$emailTo = 'Contact <your#email.com>';
$emailFrom = FilterCChars("$FTGmail");
$emailHeader = "From: $emailFrom\n"
. "MIME-Version: 1.0\n"
. "Content-Type: text/html; charset=\"UTF-8\"\n"
. "Content-Transfer-Encoding: base64\n"
. "\n";
mail($emailTo, $emailSubject, $emailBody, $emailHeader);
$successPage = '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>Success</title></head><body>Form submitted successfully. It will be reviewed soon.</body></html>';
$successPage = str_replace('<!--FIELDVALUE:latitude-->', $FTGlatitude, $successPage);
$successPage = str_replace('<!--FIELDVALUE:longitude-->', $FTGlongitude, $successPage);
$successPage = str_replace('<!--FIELDVALUE:desc-->', $FTGdesc, $successPage);
$successPage = str_replace('<!--FIELDVALUE:mail-->', $FTGmail, $successPage);
$successPage = str_replace('<!--FIELDVALUE:submit-->', $FTGsubmit, $successPage);
echo $successPage;
}
?>
I'm relatively new to WordPress and PHP, however I am trying to create my own shortcode plugin, which I have completed and is working.
However if I add more than 1 on the same page in WP, both forms submit and are not exclusive of each other.
I have search around the web, but can't find out how to easily separate the form id's, below is my plugin code:
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to '
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info.$email_form;
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
If someone can help that would be appreciated.
Thanks,
Steve
I am pretty sure you've forgotten the last attribute in the function shortcode_atts, even if it's optionnal, you need to call it.
Also, is there some code missing ?
edit : you need to id your forms otherwise the function will pick up the datas twice. call the second shortcode giving the value 'second' to teh variable $num_f like so [wptuts_contact_form_sc -your bunch of vars here- num_f="second"]
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to ',
"num_f" => 'first'
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $num_f == 'second') {
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info.$email_form;
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
To have more than two forms, you can either do it manually by calling the third block 'trird' and so on, but that's not very good practice to be honest...
If I were you I would change your code at the core, create a function that would return the form with a hidden field like so : <input type"hidden" name="hidden" value=" . $nf . "> and then instead of controling $_SERVER['REQUEST_METHOD'], you'd control the value of $_POST['n'] after checking if it's set ofc.
Here's the code I came up with :
<?php
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to ',
"nf" => '1'
), $atts));
if (isset($_POST['hidden'])) {
$hidden = $_POST['hidden'];
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
} else {
$hidden = $_POST['hidden'];
}
for ($i = 1; $i <= $nf; $i++) {
if($result != "" && $i == $hidden) {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="hidden" name="hidden" value="' . $nf . '">
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info . $email_form;
}
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
?>
Let me know if it works, (or does not) I obviously couldnt test it so there might be somehting wrong, in which case I just hope you got the whole idea behind it.