One of the less-known PHP functions is filter_var(), which checks for string patterns like email/URL/IP address and more. In this post, let's look at five practical examples of filter_var() from open-source projects.
The typical general syntax of filter_var() is this:
if (filter_var($value, FILTER_VALIDATE_EMAIL)) {    // ... means $value is a valid email}
The second parameter is one of the possible filter values:
- FILTER_VALIDATE_BOOLEAN
 - FILTER_VALIDATE_DOMAIN
 - FILTER_VALIDATE_EMAIL
 - FILTER_VALIDATE_FLOAT
 - FILTER_VALIDATE_INT
 - FILTER_VALIDATE_IP
 - FILTER_VALIDATE_MAC
 - FILTER_VALIDATE_REGEXP
 - FILTER_VALIDATE_URL
 
Now, let's see the most popular ones in action.
1. FILTER_VALIDATE_EMAIL
The first example is from an open-source project krayin/laravel-crm where filter_var() is used to validate an email address using the FILTER_VALIDATE_EMAIL filter.
public function parseEmailAddress($type){    $emails = [];     $addresses = mailparse_rfc822_parse_addresses($this->emailParser->getHeader($type));     if (count($addresses) > 1) {        foreach ($addresses as $address) {            if (filter_var($address['address'], FILTER_VALIDATE_EMAIL)) {                 $emails[] = $address['address'];            }        }    } else if ($addresses) {        $emails[] = $addresses[0]['address'];    }     return $emails;}
2. FILTER_SANITIZE_NUMBER_INT & FILTER_SANITIZE_NUMBER_FLOAT
In the open-source project koel/koel, the filter_var() function is used to filter numbers.
The FILTER_SANITIZE_NUMBER_INT filter is used for integers, and the FILTER_SANITIZE_NUMBER_FLOAT, as the name of the filter says for the floats.
Both filters can optionally have a specified range.
public function stream(Song $song, array $config = []): void{    // ...     $bitRate = filter_var(Arr::get($config, 'bit_rate'), FILTER_SANITIZE_NUMBER_INT)        ?: config('koel.streaming.bitrate');     $startTime = filter_var(Arr::get($config, 'start_time', 0), FILTER_SANITIZE_NUMBER_FLOAT);     // ...}
3. FILTER_VALIDATE_BOOLEAN
Did you know that you can check if a value is boolean using the filter_var() function? In the koel/koel, this is exactly how the FILTER_VALIDATE_BOOLEAN is used.
public function set(string $key, mixed $value): self{    $cast = self::CASTS[$key] ?? null;     $value = match ($cast) {        'boolean' => filter_var($value, FILTER_VALIDATE_BOOLEAN),         'integer' => (int) $value,        'float' => (float) $value,        default => $value,    };     // ...}
4. FILTER_VALIDATE_IP
The filter_var() has an excellent filter for IP addresses. This filter is used in the pterodactyl/panel open-source project.
Additionally, there are options to filter only IPv4 or IPv6 or not from private or reserved ranges.
public function passes($attribute, $value): bool{    if (filter_var($value, FILTER_VALIDATE_IP)) {         if ($this->schemeField && Arr::get($this->data, $this->schemeField) === 'https') {            $this->message = 'The :attribute must not be an IP address when HTTPS is enabled.';             return false;        }         return true;    }     $records = @dns_get_record($value, DNS_A + DNS_AAAA);    if (!empty($records) || filter_var(gethostbyname($value), FILTER_VALIDATE_IP)) {        return true;    }     $this->message = 'The :attribute could not be resolved to a valid IP address.';     return false;}
5. FILTER_VALIDATE_URL
Using the filter_var() function with the FILTER_VALIDATE_URL filter, it is straightforward to check if the variable is a valid URL.
In the area17/twill, this filter is used to create a validation rule.
class ValidationServiceProvider extends ServiceProvider{    public function boot()    {        // ...         Validator::extend('relative_or_secure_url', function ($attribute, $value, $parameters) {            return Str::startsWith($value, '/') || filter_var($value, FILTER_VALIDATE_URL) !== false && Str::startsWith($value, 'https');         }, 'The :attribute should be a valid url (relative or https)');         // ...    }
6. FILTER_VALIDATE_DOMAIN
You can validate the domain name with the FILTER_VALIDATE_DOMAIN filter for the filter_var() function.
An example is the open-source project of pixelfed/pixelfed.
Additionally, the FILTER_FLAG_HOSTNAME option is passed which required hostnames to start with an alphanumeric character and contain only alphanumerics or hyphens.
public static function hasValidDns($domain){    // ...     $valid = filter_var($domain, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME);      if (! $valid) {        return false;    }     return Cache::remember(self::CACHE_KEY.'valid-dns:'.$domain, 1800, function () use ($domain) {        return count(dns_get_record($domain, DNS_A | DNS_AAAA)) > 0;    });}
These are the examples of validation on the PHP level, with filter_var(). Would you add any more examples in the comments?
                                                    
                                                    
                                                    
No comments or questions yet...