Mail Chimp API and Different Arrays - php

Ok. I'm using a script from Aaron Walter to connect to MailChimps API.
There are three spots on the website and I'd like to "track" where the signup came from. I'm able to get this to work with the following code but can't wrap my mind around how to adjust this code so that there are 3 different possibilities.
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('myAPIkey');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "myLISTid";
//this line will allow me to see "headerBox" under sign up method within
// mailchimp so I know what form was used to sign up
$merge_vars = array('signup' =>'headerBox');
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars) === true) {
// It worked!
return 'Success! Check your email (and spam folder!) for your guide.';
}
else
{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
The problem I'm facing involves this line:
$merge_vars = array('signup' =>'headerBox');
"signup" will have three different values, depending on which spot they accessed the form from. I hope I've been clear enough.
EDIT:
From the code above, why wouldn't something like this work?
Put a hidden input field for each of the forms and check to see what value is given...
if($_GET['signupMethod']=='headerBox') {
$merge_vars = array('signup' =>'headerBox');
}
if($_GET['signupMethod']=='popUp') {
$merge_vars = array('signup' =>'popUp');
}
if($_GET['signupMethod']=='footer') {
$merge_vars = array('signup' =>'footer');
}
//continue with code
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars) === true) {
// It worked!
return 'Success! Check your email (and spam folder!) for your guide.';
}
else
{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}

As you stated that your form method is GET and you created a hidden field with name signupMethod, do like below:-
<?php
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('myAPIkey');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "myLISTid";
$merge_vars = ''; //define variable first and then assign values in next lines by checking it's value
if(isset($_GET['signupMethod']) && $_GET['signupMethod']=='headerBox') {
$merge_vars = array('signup' =>'headerBox');
}
if(isset($_GET['signupMethod']) && $_GET['signupMethod']=='popUp') {
$merge_vars = array('signup' =>'popUp');
}
if(isset($_GET['signupMethod']) && $_GET['signupMethod']=='footer') {
$merge_vars = array('signup' =>'footer');
}
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars) === true) {
// It worked!
return 'Success! Check your email (and spam folder!) for your guide.';
}
else
{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
?>

Related

How do i validate a company email using php preg_match function [duplicate]

I am trying to code a registration form where I am validating the email used to sign up.
In a nutshell, I want to ensure that the email ID used to register, is a company domain, and not something like gmail or yahoo.
I have the following code to check IF an email is a part of the given domain, how can I modify this to check that it ISNT in a given list of domains? (eg : gmail.com, yahoo.com,hotmail.com, etc).
return (bool) preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $domain);
Im thinking it should be along these lines, but not entirely sure :
function validate($email)
{
$error = 0;
$domains = array('gmail.com','yahoo.com','hotmail.com');
foreach($domains as $key=>$value)
{
if(preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $value)
{
$error=1;
}
}
if($error==0)
return true;
else
return false;
EDIT : I tried all the answers given here, the form still submits without a problem no matter what domain I use! (Even a non email seems to work!)
This is how I'm calling the function -
if(isset($_POST['clients_register']))
{
//Must contain only letters and numbers
if(!preg_match('/^[a-zA-Z0-9]$/', $_POST['name']))
{
$error[]='The username does not match the requirements';
}
//Password validation: must contain at least 1 letter and number. Allows characters !##$% and be 8-15 characters
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,15}$/', $_POST['password']))
{
$error[]='The password does not match the requirements';
}
//Email validation
if (validateEmail($_POST['email'])==false)
{
$error[]='Invalid E-mail';
}
//Output error in array as each line
if ( count($error) > 0)
{
foreach ($error as $output) {
echo "{$output} <br>";
}
} else {
//Syntax for SQL Insert into table and Redirect user to confirmation page
}
}
Problem is, no matter what I do, the user gets redirected to the confirmation page (Even with a name made of numbers and an email like "table".
You should do that in a separate step. First check if the e-mailaddress has a valid syntax. Than extract the domain and see if it's not in your blacklist.
function validate($email)
{
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) return false;
$domains = array('gmail.com','yahoo.com','hotmail.com');
list(, $email_domain) = explode('#', $email, 2);
return !in_array($email_domain, $domains);
}
function validateEmail($email)
{
// Etc, just an array of the blacklisted domains
$blacklistDomains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'googlemail.com'];
// Check if the email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
// Split the email after the '#' to get the domain
$emailParts = explode('#', $email);
if (in_array(end($emailParts), $blacklistDomains)) {
return false;
}
return true;
}
You'll need a pretty big list of domains.
PHP
// Suposing that $email is a valid email
function validate($email) {
$invalidDomains = array('gmail.com','yahoo.com','hotmail.com');
$parts = explode('#',$email);
$domain = $parts[1];
if(!in_array($domain,$invalidDomains)) return true;
return false;
}
Let me know if it's useful.

email domain validation in php on windows

I am asking for an email address through a form in my website. I want to validate the domain so that I can prevent fake entries I am getting right now. I am using the following code, but it dose not seem to work :
function myCheckDNSRR($hostName, $recType = '')
{
if(!empty($hostName)) {
if( $recType == '' ) $recType = "MX";
exec("nslookup -type=$recType $hostName", $result);
// check each line to find the one that starts with the host
// name. If it exists then the function succeeded.
foreach ($result as $line) {
if(eregi("^$hostName",$line)) {
echo "valid email";
}
}
// otherwise there was no mail handler for the domain
echo "invalid email";
}
echo "invalid EMAIL";
}
I am new to this and used this code from here
Please guide me. Thanks.
I guess you can simply ping like this.
function myCheckDNSRR($email_address)
{
if(!empty($email_address)) {
$hostName=strstr($email_address, '#');
$hostName=str_replace("#","www.",$hostName);
exec("ping " . $hostName, $output, $result);
if ($result == 0){
echo "valid email";
}
else{
echo "invalid email";
}
}
}
call it like
echo myCheckDNSRR("sample#gmail.com");
Use a validation lib like https://docs.zendframework.com/zend-validator/validators/email-address/
$validator = new Zend\Validator\EmailAddress();
if ($validator->isValid($email)) {
// email appears to be valid
} else {
// email is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
Create a table in your DB for storing an email link code. When someone registers, mark the user as unactivated until he clicks the link in the email. This way, you know it's real, and can activate the user.

Check if the email is belong to student email which contain edu in laravel

I want to check the registered users is student by validating the registered email. I have a table which contain multiple education email domain name such as #mmu.edu.my, #taylor.edu.uk and etc. First the controller should get all available name from database and validate the user email. Then will assign different roles according their university. But the question is how to check the email with each of the available domain name in database.
In my controller i had get the registered user email.
$user_email=$user_info->email;
This is example of the email
alex_9237502834#taylor.edu.uk
Is they any reference for me to learn how to validate?
I'd just cycle through the valid domains as an array, like this:
<?php
$validDomains = array('mmu.edu.my', 'taylor.edu.uk');
function validEmail($email, $validDomains) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$email_parts = explode('#', $email); // [0] will be ben, [1] will be mmu.edu.my
// Valid email address. Does it match anything in our domain whitelist?
foreach($validDomains as $validDomain) {
if (strtolower($validDomain) == $email_parts[1]) {
return true;
}
}
}
return false; // No matches
}
var_dump( validEmail('ben#mmu.edu.my', $validDomains) ); // TRUE
var_dump( validEmail('ben#randomdomain.com', $validDomains) ); // FALSE
var_dump( validEmail('clearlynotanemail', $validDomains) ); // FALSE
var_dump( validEmail('jow#taylor.edu.uk', $validDomains) ); // TRUE
so there are multiple domains i guess? and you need to check the email domain belongs to one of them or not.
so first of all get a query by which you will you will get all the domain.
then
$user_email = explode('#',$entered_email);
$user_email_domain = $user_email[1];
foreach($sql_returned as $sql)
{
if($sql->email == $user_email_domain)
{
do what you want
}
else
{
do something else
}
}
First split the email using "#" sign ..
$user_email=$user_info->email;
$splitted = explode('#',$user_email);
if($splitted[1] == "mmu.edu.my")
{
// attach role here
}
elseif(....)
{
}

Domain specific email validation

I am trying to code a registration form where I am validating the email used to sign up.
In a nutshell, I want to ensure that the email ID used to register, is a company domain, and not something like gmail or yahoo.
I have the following code to check IF an email is a part of the given domain, how can I modify this to check that it ISNT in a given list of domains? (eg : gmail.com, yahoo.com,hotmail.com, etc).
return (bool) preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $domain);
Im thinking it should be along these lines, but not entirely sure :
function validate($email)
{
$error = 0;
$domains = array('gmail.com','yahoo.com','hotmail.com');
foreach($domains as $key=>$value)
{
if(preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $value)
{
$error=1;
}
}
if($error==0)
return true;
else
return false;
EDIT : I tried all the answers given here, the form still submits without a problem no matter what domain I use! (Even a non email seems to work!)
This is how I'm calling the function -
if(isset($_POST['clients_register']))
{
//Must contain only letters and numbers
if(!preg_match('/^[a-zA-Z0-9]$/', $_POST['name']))
{
$error[]='The username does not match the requirements';
}
//Password validation: must contain at least 1 letter and number. Allows characters !##$% and be 8-15 characters
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,15}$/', $_POST['password']))
{
$error[]='The password does not match the requirements';
}
//Email validation
if (validateEmail($_POST['email'])==false)
{
$error[]='Invalid E-mail';
}
//Output error in array as each line
if ( count($error) > 0)
{
foreach ($error as $output) {
echo "{$output} <br>";
}
} else {
//Syntax for SQL Insert into table and Redirect user to confirmation page
}
}
Problem is, no matter what I do, the user gets redirected to the confirmation page (Even with a name made of numbers and an email like "table".
You should do that in a separate step. First check if the e-mailaddress has a valid syntax. Than extract the domain and see if it's not in your blacklist.
function validate($email)
{
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) return false;
$domains = array('gmail.com','yahoo.com','hotmail.com');
list(, $email_domain) = explode('#', $email, 2);
return !in_array($email_domain, $domains);
}
function validateEmail($email)
{
// Etc, just an array of the blacklisted domains
$blacklistDomains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'googlemail.com'];
// Check if the email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
// Split the email after the '#' to get the domain
$emailParts = explode('#', $email);
if (in_array(end($emailParts), $blacklistDomains)) {
return false;
}
return true;
}
You'll need a pretty big list of domains.
PHP
// Suposing that $email is a valid email
function validate($email) {
$invalidDomains = array('gmail.com','yahoo.com','hotmail.com');
$parts = explode('#',$email);
$domain = $parts[1];
if(!in_array($domain,$invalidDomains)) return true;
return false;
}
Let me know if it's useful.

How To solve dis synchronize of form Validation?

I am wondering if anyone out there can help with my form Validation Please?
I am having a few problems trying to synchronized out how certain bits of the actual structure of the script works together.
<?php
$flag="OK"; // This is the flag and we set it to OK
$msg=""; // Initializing the message to hold the error messages
if(isset($_POST['Send'])){
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
if($key!=num_key){
$msg=$msg."Your Key not valid! Please try again!<BR>";
$flag="NOTOK";
}
else{
$msg=$msg."Your Key is valid!<BR>";
$flag="OK";
}
}
$email=$_POST['email'];
echo "Your Email: ".$email." is";
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$msg=$msg."Invalid email<BR>";
$flag="NOTOK";
}else{
$msg=$msg."Valid Email<BR>";
$flag="OK";
}
$password=$_POST['password'];
if(strlen($password) < 5 ){
$msg=$msg."( Please enter password of more than 5 character length )<BR>";
$flag="NOTOK";
}
if($flag <>"OK"){
echo "$msg <br> <input type='button' value='Retry' onClick='history.go(-1)'>";
}else{ // all entries are correct and let us proceed with the database checking etc …
}
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_POST['email']))
{//if "email" is filled out, proceed
$mailcheck = spamcheck($_POST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
}
?>
the problem, when email valid, password valid, though key is invalid the warning of key disappear, it mean passed too... and also the spamcheck doesn't look work..
You don't have to set the flag to 'OK' or a previous error get masked, as you already noted.
If all the check are ok, the flag remains in valid state and you can pass on, otherwise, if one of the check fails the flag reports the incorrect state.
$flag="OK"; // This is the flag and we set it to OK
$msg=""; // Initializing the message to hold the error messages
if(isset($_POST['Send'])) {
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
if($key!=$num_key){
$msg=$msg."Your Key not valid! Please try again!<BR>";
$flag="NOTOK";
} else {
$msg=$msg."Your Key is valid!<BR>";
}
}
$email=$_POST['email'];
echo "Your Email: ".$email." is";
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$msg=$msg."Invalid email<BR>";
$flag="NOTOK";
}else{
$msg=$msg."Valid Email<BR>";
}
$password=$_POST['password'];
if(strlen($password) < 5 ){
$msg=$msg."( Please enter password of more than 5 character length )<BR>";
$flag="NOTOK";
}
if($flag <>"OK"){
echo "$msg <br> <input type='button' value='Retry' onClick='history.go(-1)'>";
} else {
// all entries are correct and let us proceed with the database checking etc …
}
Said that I would use a different approach, for example using boolean values other than a string named flag. You can obtain a more fluent code calling it something like $inputIsvalid.
Other nags: Sometimes you add the messages to a $msg variable, other you issue an echo, maybe it is an oversight.
There is a lot of room for improvements, as every other code, I will address just some of the easy issues, for examples I will not check if the variables are set or not.
$inputIsValid=true; // This is the flag and we set it to OK
$messages = array(); // Initializing the message to hold the error messages
if(isset($_POST['Send'])) {
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
if($key!=$num_key){
$messages[]= 'Your Key not valid! Please try again!';
$inputIsValid=false;
} else {
$messages[]'Your Key is valid!';
}
}
$email=$_POST['email'];
$emailRegex='^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$';
$emailIsValid = eregi($emailRegEx, $email);
$messages[]= 'Your Email: '.$email.' is ' .($emailIsValid? 'Valid':'Invalid');
$inputIsValid = $inputIsValid && emailIsValid;
$password=$_POST['password'];
if(strlen($password) < 5 ){
$messages[]='( Please enter password of more than 5 character length )';
$inputIsValid=false;
}
if(!inputIsValid){
$messages[]='<input type='button' value='Retry' onClick='history.go(-1)'>';
echo join('<br/>', $messages);
} else {
// all entries are correct and let us proceed with the database checking etc …
}
Another approach should be (the functions are quite simple, but you can modify the validation policy of the different components without affecting the main code):
function validateKey() {
if(!isset($_POST['Send'])) {
return true;
}
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
return $key==$num_key;
}
function validateEmail($email) {
$emailRegex='^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$';
return eregi($emailRegEx, $email);
}
function validatePassword($password) {
return strlen($password) < 5;
}
$inputIsValid=true; // This is the flag and we set it to OK
$messages = array(); // Initializing the message to hold the error messages
if(validateKey()) {
$messages[]'Your Key is valid!';
} else {
$messages[]= 'Your Key not valid! Please try again!';
$inputIsValid=false;
}
$emailIsValid = validateEmail($_POST['email']);
$messages[]= 'Your Email: '.$email.' is ' .($emailIsValid? 'Valid':'Invalid');
$inputIsValid = $inputIsValid && emailIsValid;
$password=;
if(!validatePassword($_POST['password']){
$messages[]='( Please enter password of more than 5 character length )';
$inputIsValid=false;
}
if(!inputIsValid){
$messages[]='<input type='button' value='Retry' onClick='history.go(-1)'>';
echo join('<br/>', $messages);
} else {
// all entries are correct and let us proceed with the database checking etc …
}
Spam function:
why are you using Constant different than the boolena values?
(TRUE is different from true and FALSE is different from false)
You can rewrite the function like this in order to obtain the desired behaviour.
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
return filter_var($field, FILTER_VALIDATE_EMAIL);
}
if (isset($_POST['email'])) {//if "email" is filled out, proceed
$mailcheck = spamcheck($_POST['email']);
if (!$mailcheck) {
echo "Invalid input";
}
}
Each of you tests sets flag to "OK" or "NOTOK" overwriting decisions made by previous tests.
You could start with $flag = true;. And only if a test decides that the input is unsatisfying it sets $flag=false.
Or you can remove $flag altogether and check if 0===strlen($msg) after the tests.

Categories