Skip to content

Instantly share code, notes, and snippets.

@jesinwp
Last active May 25, 2018 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesinwp/c29dc9fe10d3ee2745724c8c45f46712 to your computer and use it in GitHub Desktop.
Save jesinwp/c29dc9fe10d3ee2745724c8c45f46712 to your computer and use it in GitHub Desktop.
validate_email() function with transients
<?php
//Function which sends the email to Mailgun to check it
public function validate_email( $emailID ) {
global $pagenow, $wp;
//If the format of the email itself is wrong return false without further checking
if( ! filter_var( $emailID, FILTER_VALIDATE_EMAIL ) )
return FALSE;
//If no API was entered don't do anything
if( ! isset( $this->options['mailgun_pubkey_api'] ) || empty( $this->options['mailgun_pubkey_api'] ) )
return TRUE;
if ( "edit.php" == $pagenow && "shop_order" == $wp->query_vars['post_type'] ) {
return true;
}
$emails = get_transient( 'mailgun_validated_emails' );
$emailID = strtolower( $emailID );
if ( isset( $emails[ $emailID ] ) ) {
return ( 1 == $emails[ $emailID ] ) ? $emailID : false;
}
$args = array(
'sslverify' => FALSE,
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( "api:".$this->options['mailgun_pubkey_api'] )
)
);
//Send the email to Mailgun's email validation service
$response = wp_remote_request( "https://api.mailgun.net/v3/address/validate?address=".urlencode($emailID), $args );
//If there was a HTTP or connection error pass the validation so that the website visitor doesn't know anything
if( is_wp_error( $response ) || isset( $response['error'] ) || '200' != $response['response']['code'] )
return TRUE;
//Extract the JSON response and return the result
$result = json_decode( $response['body'], true );
if ( ! $emails ) $emails = array();
$emails[ $emailID ] = ( $result['is_valid'] ? '1' : '0' );
set_transient( 'mailgun_validated_emails', $emails, MONTH_IN_SECONDS );
return $result['is_valid'] ? $emailID : false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment