Fixing 'Call to Undefined Function' Filter_Var() in PHP

I host a lot of websites in the Amazon cloud on EC2. I recently discovered that all email one site was sending was being rated as spam and never seen by the recipient. This meant that new users didn't get the verification email required to complete signup. It appears that EC2 IP addresses can have a dodgy reputation among email providers. Another web publisher described these problems on AWS Developer Forums.

PHP elephant iconSince then I've been rewriting my code to deliver emails with SendGrid, a service designed to avoid all that agita. SendGrid has an API and PHP library that are simple to implement.

While converting a mail script on a non-EC2 server I encountered the following error:

PHP Fatal error: Call to undefined function SendGrid\Mail\filter_var() in sendgrid-php/lib/mail/Mail.php on line 1008

This occurred because the SendGrid PHP library uses filter_var(), a function that was introduced in a later version of PHP than the one on my server.

I'm retiring the server soon, so I didn't want to upgrade PHP just to fix the problem. Rewriting SendGrid's PHP code to replace the missing function also would be difficult. Fortunately I found an ingenious solution from a Joomla developer who encountered the same problem: Create your own filter_var() function that does nothing but return the text it was supposed to filter:

if (!function_exists('filter_var')){
    function filter_var($value, $filter_type) {
        return $value;

Putting this in the mail script caused my version of filter_var() to be called instead of the built-in one that SendGrid's code expected. When I move to a new server with PHP 7, it will use the real function again.

I had no idea you could do this in PHP. I thought there was a wall between built-in functions and user-defined functions.

There's at least one aspect of being a programmer that's like being Tony Hawk. You sometimes experience the elation of "I never knew you could do this and now that I can I want to do it all the time."

Add a Comment

All comments are moderated before publication. These HTML tags are permitted: <p>, <b>, <i>, <a>, and <blockquote>. This site is protected by reCAPTCHA (for which the Google Privacy Policy and Terms of Service apply).