How to Validate an Email Address for Correct Syntax in PHP

Cloudmersive
2 min readMar 30, 2020

--

Email validation has so many good uses, whether it is for newsletter subscription, account activation, or something else. A basic checking of syntax is generally enough to weed out the majority of invalid email addresses. Rather than go through all of the trouble of setting this up manually, how about we use an API to do it for us instead?

To access our API, we will need to install its client via this command for Composer.

composer require cloudmersive/cloudmersive_validate_api_client

Now we are able to call functions from the API, namely emailPost:

<?phprequire_once(__DIR__ . '/vendor/autoload.php');// Configure API key authorization: Apikey$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed// $config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('Apikey', 'Bearer');$apiInstance = new Swagger\Client\Api\EmailApi(// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.// This is optional, `GuzzleHttp\Client` will be used as default.new GuzzleHttp\Client(),$config);$value = "value_example"; // string | Email address to validate, e.g. \"support@cloudmersive.com\".    The input is a string so be sure to enclose it in double-quotes.try {$result = $apiInstance->emailPost($value);print_r($result);} catch (Exception $e) {echo 'Exception when calling EmailApi->emailPost: ', $e->getMessage(), PHP_EOL;}?>

All done! Any email entered as the value will be checked for syntax. Should you need a more advanced form of validation that also queries the email server, try out our related function called emailFullValidation.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet