-
-
Save jesinwp/c29dc9fe10d3ee2745724c8c45f46712 to your computer and use it in GitHub Desktop.
validate_email() function with transients
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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