Mailchimp false positive on multiple list subscribe - php

Here is my code which I am using to subscribe users to multiple Mailchimp lists in which they choose and is posted to this file by an ajax request. Here is the code:
So for some reason this returns a success from Mailchimp, but it doesn't actually subscribe to the lists I have entered. I have confirmed the list ids are correct and fields are too.
(I have removed all reference to the actual IDs)
<?php
include 'MailChimp.php';
$mailchimp = new MailChimp('MYAPI_KEY'); //I have my code in here
$newsletter_keyarray = array(
"List one" => "listoneid",
"List two" => "listtwoid",
"List three" => "listthreeid",
"List four" => "listfourid"
);
$any_errors = false;
foreach ($_POST['lists'] as $key => $list) {
if(in_array($list, $newsletter_keyarray)){
$merge_vars_array = array(
'EMAIL' => $_POST['email']
);
if($list == "List one"){
$merge_vars_array['MMERGE1'] = $_POST['fname'];
$merge_vars_array['MMERGE2'] = $_POST['sname'];
$merge_vars_array['MMERGE3'] = $_POST['org'];
}else if($list == "List two"){
$merge_vars_array['FNAME'] = $_POST['fname'];
$merge_vars_array['LNAME'] = $_POST['sname'];
$merge_vars_array['MMERGE4'] = $_POST['job'];
$merge_vars_array['MMERGE5'] = $_POST['org'];
}else if($list == "List three"){
$merge_vars_array['FNAME'] = $_POST['fname'];
$merge_vars_array['LNAME'] = $_POST['sname'];
$merge_vars_array['MMERGE3'] = $_POST['org'];
$merge_vars_array['MMERGE4'] = $_POST['job'];
}else if($list == "List four"){
$merge_vars_array['FNAME'] = $_POST['fname'];
$merge_vars_array['LNAME'] = $_POST['sname'];
$merge_vars_array['MMERGE4'] = $_POST['job'];
$merge_vars_array['MMERGE5'] = $_POST['org'];
}
$mailResults = $mailchimp->call('lists/subscribe', array(
'id' => $newsletter_keyarray[$list],
'email' => array('email' => $_POST['email']),
'merge_vars' => $merge_vars_array,
'double_optin' => false
));
if(isset($mailResults['status']) && $mailResults['status'] == 'error'){
$any_errors = true;
}
}
}
//enter api and userdetails here
$response_array = array();
if($any_errors){
header('Content-type: application/json');
$response_array['status'] = 'error';
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$response_array['message'] = 'The email you have entered is not valid';
}else if(isset($mailResults['error']) && $mailResults['error'] != ""){
$response_array['message'] = $mailResults['error'];
}
echo json_encode($response_array);
}else{
header('Content-type: application/json');
$response_array['status'] = 'success';
echo json_encode($response_array);
}
?>

I have figured it out kind of stupid of me.
The issue was in_array which compares the value rather than the key. So in the end I used array_key_exists

Related

Can't get a JSON object response to an Ajax request on live server

I have a form which when submitted made request to the server through ajax using php curl. Everything worked perfectly in my local environment(wamp) but when I moved it to live server, it doesn't return any json response.
I can't figure out why it worked in wampserver but not on live server?
php code
<?php
if(isset($_POST['logins']))
{
require_once 'functions.php';
require_once("cons.php");
$licence = $_POST['licence'];
$url = "http://tapi.com/apis/User/api.php?licence=".$licence;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$data = json_decode($response, true);
$msg = $data['message'];
$lic = $data['licence'];
$p = $data['period'];
$u = $data['user'];
$sta = $data['status'];
if($msg == 'Successfully Validated!')
{
//$_SESSION['data'] = array($data, true);
$url = "http://tapi.com/apis/User/api.php?lic=".$lic;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$data = json_decode($response, true);
$msg = $data['message'];
if($msg == 'inserted')
{
$host = $_SERVER['HTTP_HOST'];
$hostaddrs = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$sys_info = php_uname();
$exp_date = encryptIt2($p);
$date = date('Y-m-d');
$ts = encryptIt2($date);
$queryu = "insert into tray(host, license, validity, et)values('$host', '$lic', '$exp_date', '$ts')";
$get = mysqli_query($mysqli,$queryu);
if($get){
echo "yes";
}else{
echo $mysqli -> error;
}
}else{
echo $msg;
}
}
else
{
echo $data['message'];
}
}
?>
jQuery code
function licenceForm()
{
var data = $("#licence-form").serialize();
$.ajax({
type : 'POST',
url : 'ext/b0a012.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-login").html('<img src="assets/img/find.png"
width="26" height="25"> Please wait...');
},
success : function(response)
{
if(response=="yes"){
$(".hideit").hide();
$(".shows").show();
setTimeout('window.location.href = "index.php"; ',2000);
}else{
$("#error").fadeIn(1000,function(){
$("#error").html('<div class="alert alert-danger text center">
<img src="assets/img/attention.png" width="45" height="40" />
<br/> '+response+'</div>');
$("#btn-login").html('Error occured. Try again.');
});
}
}
});
return false;
}
API
if (isset($_GET['licence']) && $_GET['licence']!="") {
$licence = $con->real_escape_string($_GET['licence']);
//$licence = "M7RS-8C46-APSE";
$selec = mysqli_query($con, "SELECT licence, period, users FROM licence_used WHERE licence='$licence'");
$mrow = mysqli_fetch_array($selec);
$count = mysqli_num_rows($selec);
if($count > 0){
$q2 = mysqli_query($con,"select count(licence) use_count FROM licence_used WHERE licence='$licence'");
$get = mysqli_fetch_array($q2);
//query 2
$selec = mysqli_query($con, "SELECT licence,
period, users FROM licence_used WHERE licence='$licence'");
$users = $mrow['users'];
$num = $get['use_count'];
if($num == $users){
$user_arr=array(
"status" => false,
"message" => "Licence key entered has been used up by ".$num." users. Please purchase another licence.",
);
}else{
while($row = mysqli_fetch_array($selec)){
// create array
$user_arr=array(
"status" => true,
"message" => "Successfully Validated!",
"licence" => $mrow['licence'],
"period" => $mrow['period'],
"user" => $mrow['users'],
"mstatus" => $mrow['status']
);
}
}
}else{
$select = mysqli_query($con, "SELECT licence, period, users FROM licence WHERE licence='$licence'");
if(mysqli_num_rows($select) == 0){
$user_arr=array(
"status" => false,
"message" => "Invalid Licence Key Entered. Please contact the software company.",
);
}else{
while($row = mysqli_fetch_array($select)){
// create array
$user_arr=array(
"status" => true,
"message" => "Successfully Validated!",
"licence" => $row['licence'],
"period" => $row['period'],
"user" => $row['users'],
"mstatus" => $row['status']
);
}
}
}
}
header("Content-Type:application/json");
print_r(json_encode($user_arr));
I used postman to test it and it worked. Do anyone know what the issue might be? Thanks.

how to get value from text file in php

I have script that make comparison between value from page php and data store in txt file, and then it will do some special code.
Content of txt file (account.txt)
F: user pass { expire=date; afexpire=date; email=email#gmail.com; Country=Germani; visit_from=none; ip=none; hosted=none }
F: mike fghg58g { expire=2016-05-24; afexpire=2015-5-24 17; email=mike#gmail.com; Country=uk; visit_from=none; ip=none; hosted=none }
F: adresson f5849dh9d { expire=2016-11-01; afexpire=2015-11-01 17; email=mike#gmail.com; Country=Germani; visit_from=none; ip=none; hosted=none }
my script
<?php
$user = "Mike"; // user that is inserted in page form
$email = "mike#gmail.com"; // email that is inserted in page form
$userFile = "Mike"; // user in txt file
$emailFile = "mike#gmail.com"; // email in txt file
if( $user == $userFile && $email == $emailFile ) {
echo "The user and email is used";
} elseif( $user == $userFile && $email != $emailFile ) {
echo "The user is used";
} else{
// do special code
}
I don't know how to read file txt from path and change user and email in file to value to make comprison
$userFile = "Mike"; // user in txt file (account.txt)
$emailFile = "mike#gmail.com"; // email in txt file (account.txt)
This is my spcial script that make output in (account.txt)
<?php
if (isset($_POST["g-recaptcha-response"])) {
$name = $_POST['name'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$country = $_POST['country'];
$plan = $_POST['plan'];
$quantity = $_POST['quantity'];
$payment = $_POST['payment'];
$reciever = $_POST['reciever'];
$captcha = $_POST['g-recaptcha-response'];
$message_user = $_POST['message'];
$serverip = $_POST['REMOTE_ADDR'];
$to = 'sup.alphas#gmail.com';
$parts = explode("#", $email);
$sufemail = $parts[0];
// $sufemail = substr(strstr($email, '#'), 1); for domain//
$subject_form = 'Request new account by '.$sufemail.'';
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if name has been entered
if (!$_POST['user']) {
$errUser = 'Please enter your username';
}
// Check if name has been entered
if (!$_POST['pass']) {
$errPass = 'Please enter your password';
}
// Check if email has been entered and is valid
if (!$_POST['email']) {
$errEmail = 'Please enter a valid email address';
}
if (!$_POST['country']) {
$errCountry = 'Please enter your country';
}
if (!$_POST['plan']) {
$errPlan = 'Please enter your plan';
}
if (!$_POST['quantity']) {
$errQuantity = 'Please enter your quantity';
}
if (!$_POST['payment']) {
$errPayment = 'Please enter your method of payment';
}
if (!$_POST['g-recaptcha-response']) {
$errCaptcha = 'Please enter captcha';
}
// If there are no errors, send the email
if (!$errName && !$errUser && !$errPass && !$errEmail && !$errCountry && !$errPlan && !$errQuantity && !$errPayment && !$errCaptcha) {
// Start Create new account //
$dateadd = date('Y-m-d', strtotime("$plan"));
$datetry = date('Y-m-d H', strtotime("+1 day"));
$handle = fopen('/usr/www/users/alphacz/alpha/phpm/account.cfg', 'a');
fwrite($handle, 'F: ' . $_POST["user"] . ' ' . $_POST["pass"] . ' { expire=' . $datetry . '; afexpire=' . $dateadd . '; email=' . $email . '; Country=' . $country . '; visit_from=none; ip=none; hosted=' . $_POST['REMOTE_ADDR'] . " }\r\n");
fclose($handle);
Help me, please
Thank you
You can check a needle in a haystack which is your account file here.
username pattern is "F: {user} pass {..."
email pattern is "; email={email}; Country="
Note: You must also think that this excample check keywords incasesensitive, so
when searching and inserting, you should convert keywords to lowercase
$user_used = userExists('Mike');
$email_used = emailExists('mike#gmail.com');
if ($user_used && $email_used)
{
echo 'The user and email is used';
}
elseif ($user_used) {
echo 'The user is used';
}
else
{
//do special code
}
function userExists($user)
{
return (exec('grep ' . escapeshellarg('F: ' . $user . ' ') . ' {file-path}'));
}
function emailExists($email)
{
return (exec('grep ' . escapeshellarg('; email=' . $email . ';') . ' {file-path}'));
}
We could fix your current code to read from the file, but instead we first rewrite your code which writes to the file, so it will be way easier to read from the file afterwards.
(Since you only show part of the script which writes to the file I can only rewrite that part.)
Changes
JSON format for the file
Instead of writing your data into the file in a custom format we will save the data in JSON format. You can easily work with JSON in PHP since it has built-in functions to work with it.
$_POST ↔ $_SERVER ?
At some point you use $_POST['REMOTE_ADDR'], but I assume that you wanted to use $_SERVER["REMOTE_ADDR"]. See: http://php.net/manual/en/reserved.variables.server.php.
!$XY
While using !$XY as condition may work sometimes it isn't very practical. Since it simply negates the value and then checks if it is a truthy or falsey value and should enter the if statement or not. So I would recommend you to use !empty() to check if your input is set and is not empty.
Code
<?php
if (isset($_POST["g-recaptcha-response"])){
$checkPostIndices = ["name", "user", "pass", "email", "phone", "country", "plan", "quantity", "payment", "reciever", "g-recaptcha-response", "message"];
$data = [];
$errors = [];
$errorMessages = [
"name" => "Please enter your name",
"user" => "Please enter your username",
"pass" => "Please enter your password",
"email" => "Please enter a valid email address",
"phone" => "Please enter your phone number",
"country" => "Please enter your country",
"plan" => "Please enter your plan",
"quantity" => "Please enter your quantity",
"payment" => "Please enter your method of payment",
"reciever" => "Please eneter a reciever",
"g-recaptcha-response" => "Please enter captcha",
"message" => "Please enter a message",
];
foreach($checkPostIndices as $index){
if(!empty($_POST[$index])){
$data[$index] = $_POST[$index];
} else {
$errors[] = $errorMessages[$index];
}
}
$data["serverip"] = $_SERVER["REMOTE_ADDR"];
$to = "sup.alphas#gmail.com";
$sufemail = explode("#", $data["email"])[0];
$subject_form = "Request new account by " . $sufemail;
if(!empty($errors)){
$fileData = array_intersect_key($data, ["user", "pass", "email", "country", "serverip"]);
$fileData["dateadd"] = date("Y-m-d", strtotime($data["plan"]));
$fileData["datetry"] = date("Y-m-d H", strtotime("+1 day"));
$file = file_get_contents("/usr/www/users/alphacz/alpha/phpm/account.cfg");
$file = empty($file) ? [] : json_decode($file, TRUE);
$file[] = $fileData;
file_put_contents("/usr/www/users/alphacz/alpha/phpm/account.cfg", json_encode($file));
}
}
?>
So now after that your data should be stored in JSON like this:
[
{"key":"data"}
//...
]
And then you can easily use json_decode() to decode your file into an array, loop through the array and check if the email and user are already used.
Code
<?php
$user = "Mike";
$email = "mike#gmail.com";
$file = file_get_contents("/usr/www/users/alphacz/alpha/phpm/account.cfg");
$data = json_decode($file, TRUE);
foreach($data as $v){
if($v["user"] == $user && $v["email"] == $email){
echo "Email and user already used";
}
}
?>

Store form data into wordpress database

I have created a simple html form to test, how I can insert data in wpdb. I know how to do it in PHP but in wordpress I am getting confused!
global $wpdb;
if (isset($_POST['submit'])) {
$name = $_POST['r1s1']; //Here r1s1 is name of the form control
$email = $_POST['r2s1'];
$contact = $_POST['r3s1'];
$address = $_POST['r5s1'];
if ($name != '' || $email != '') {
$post = $wpdb->insert(
'table', array(
'feild' => $name,
'dev' => $email,
'tenant' => $contact,
'mod' => $address,
), array(
'%s',
'%s',
'%s',
'%s'
)
);
echo $post;
if ($post) {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
} else {
echo "<br/><br/><span>Insertion Failed...!!</span>";
}
} else {
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
When I click on submit button then it shows message insertion failed...!! ( Message that I am printing via echo). This code is written in template. What I am doing wrong?
global $wpdb;
$wpdb->insert( 'table_name', array( 'field_name' => $_POST['r1s1'], 'field_name' => $_POST['r2s1'],'field_name' => $_POST['r3s1'],'field_name' => $_POST['r4s1']) );
Try This one
You can try below code?
global $wpdb;
$table_name = $wpdb->prefix . "your_table_name";
if (isset($_POST['submit'])) {
$name = $_POST['r1s1']; //Here r1s1 is name of the form control
$email = $_POST['r2s1'];
$contact = $_POST['r3s1'];
$address = $_POST['r5s1'];
$data = array(
'feild' => $name,
'dev' => $email,
'tenant' => $contact,
'mod' => $address
);
if ($name != '' || $email != '') {
$result = $wpdb->insert($table_name, $data);
if ($result) {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
} else {
echo "<br/><br/><span>Insertion Failed...!!</span>";
}
} else {
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}

Unable To echo an HTML <form></form> within PHP

I am trying to echo an HTML form within PHP but I just can't get it done.
It just echo pre-formatted HTML. I ain't getting the form.
Here is my PHP script
do-reset.php
<?php
require_once 'connect.php';
session_start();
if($_SERVER['REQUEST_METHOD'] === 'GET') {
if(isset($_GET['email']) && !empty($_GET['email']) && isset($_GET['hash']) && !empty($_GET['hash'])) {
$email = htmlentities(mysqli_real_escape_string($connection, trim($_GET['email'])));
$hash = htmlentities(mysqli_real_escape_string($connection, trim($_GET['hash'])));
$search_query = "SELECT email, hash, status FROM users WHERE email = '{$email}' AND forgot_password_hash = '{$hash}' AND
status = '1'";
$do_search_query = mysqli_query($connection, $search_query);
if($do_search_query) {
$count_rows = mysqli_num_rows($do_search_query);
if($count_rows > 0) {
$_SESSION['email'] = $email;
$_SESSION['hash'] = $hash;
echo "<form method='post' action='do-reset.php'><input type='password' name='password'><br><input type='submit' value='Reset My Password'></form>";
}
else {
$data = array("result" => -3, "message" => "Invalid URL");
}
}
else {
$data = array("result" => -2, "message" => "Something Went Wrong! Try Again Later.");
}
}
else
{
$data = array("result" => -1, "message" => "Certain Request Parameters Are Missing!");
}
}
else {
$data = array("result" => 0, "message" => "Incorrect Request Method!");
}
mysqli_close($connection);
/* JSON Response */
header('Content-type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);
?>
1.: Remove the header('Content-type: application/json');
This will basically tell the browser to display the output as text.
2.:
to preserve formatting, you can use <pre>-tags:
echo "<pre>";
echo json_encode($data, JSON_PRETTY_PRINT);`
echo "</pre>";
Different approach:
only set content type to application/json when the $data-array is filled
if(!empty($data)){
header('Content-type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);
}
I found a way out! $type_json did the trick for me.
<?php
require_once 'connect.php';
session_start();
$type_json = true;
if($_SERVER['REQUEST_METHOD'] === 'GET') {
if(isset($_GET['email']) && !empty($_GET['email']) && isset($_GET['hash']) && !empty($_GET['hash'])) {
$email = htmlentities(mysqli_real_escape_string($connection, trim($_GET['email'])));
$hash = htmlentities(mysqli_real_escape_string($connection, trim($_GET['hash'])));
$search_query = "SELECT email, hash, status FROM users WHERE email = '{$email}' AND forgot_password_hash = '{$hash}' AND
status = '1'";
$do_search_query = mysqli_query($connection, $search_query);
if($do_search_query) {
$count_rows = mysqli_num_rows($do_search_query);
if($count_rows > 0) {
$_SESSION['email'] = $email;
$_SESSION['hash'] = $hash;
$type_json = false;
echo "<form method='post' action='do-reset.php'><input type='password' name='password'><br><input type='submit' value='Reset My Password'></form>";
}
else {
$data = array("result" => -3, "message" => "Invalid URL");
}
}
else {
$data = array("result" => -2, "message" => "Something Went Wrong! Try Again Later.");
}
}
else
{
$data = array("result" => -1, "message" => "Certain Request Parameters Are Missing!");
}
}
else {
$data = array("result" => 0, "message" => "Incorrect Request Method!");
}
mysqli_close($connection);
/* JSON Response */
if($type_json) {
header('Content-type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);
}
?>
PHP is executed on the server side and is treated as a script instead of a markup language, meaning the HTML on the requested page doesnt matter to the server at all it only cares about the PHP. so if you did
<?php
if(true) {
?>
<form>Hello</form>
<?php
}
?>
the html form will only be displayed with the text hello if the statement is true, which true always is true ofcourse. you could replace this with any statement, for example to check if someone hes entered something in a field from the form they submitted.
hope this helps!

Looping correctly though array

Okay so I'm looping through the results that contains two question IDs and two answers and I'm trying to match the two answers with the two answers from the form submission.
I'm not sure what I'm doing wrong.
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
//Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc,$_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc,$_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc,$_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc,$_POST['question1']);
$question2 = mysqli_real_escape_string($dbc,$_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if (($answer == $answer1Post) && ($answer == $answer2Post)) {
} else {
$errors = true;
$message = "Your answers did not match the answers inside the database!";
$output = array('errorsExist' => $errors, 'message' => $message);
}
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
//Output the result
$output = json_encode($output);
echo $output;
?>
Since your question is not clear in the first place, so I'm assuming that the question you are asking is "why you're not getting any matching results, when you've the correct answers in the database?". Please correct me, if this is wrong.
The logic can be like this:-
<?php
// Include the database page
require ('../inc/dbconfig.php');
require ('../inc/global_functions.php');
// Login submitted
if (isset($_POST['submit'])) {
// Errors defined as not being any
$errors = false;
if (trim($_POST['answer1']) == '') { $errors = true; }
if (trim($_POST['answer2']) == '') { $errors = true; }
// Error checking, make sure all form fields have input
if ($errors) {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => $errors, 'message' => $message);
} else {
$userID = mysqli_real_escape_string($dbc, $_POST['userID']);
$answer1Post = mysqli_real_escape_string($dbc, $_POST['answer1']);
$answer2Post = mysqli_real_escape_string($dbc, $_POST['answer2']);
$question1 = mysqli_real_escape_string($dbc, $_POST['question1']);
$question2 = mysqli_real_escape_string($dbc, $_POST['question2']);
$query = "SELECT * FROM manager_users_secretAnswers WHERE userID = '".$userID."'";
$result = mysqli_query($dbc, $query);
// Count number of returned results from query
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$answer = $row['answer'];
// Comparing the database password with the posted password
if ($answer == $answer1Post) {
// The first answer is correct
$errors = false;
$message = "Your first answer is correct!";
} else if ($answer == $answer2Post) {
// The second answer is correct
$errors = false;
$message = "Your second answer is correct!";
} else {
$errors = true;
$message = "Your answers did not match the answers inside the
}
$output = array('errorsExist' => $errors, 'message' => $message);
}
} else {
$errors = true;
$message = "We did not find any answers for your questions! Please consult the site administrator!";
$output = array('errorsExist' => $true, 'message' => $message);
}
}
}
// Output the result
$output = json_encode($output);
echo $output;
?>
It's better to have more segregation of logical conditions. In this case, it's your two answers to check for.
Hope it helps.

Categories