PHP - Filter_var alternative?

5.8k Views Asked by At

I built a php script to output data posted in a form, but I ran into a problem. The server the website is going to run on, runs PHP 5.1.6. This version of PHP does not support filter_var.

I need to know an alternative on short term (preferably yesterday), and can't find something straight forward on Google or Stack Overflow.

Mayhap someone here ran into the same issue in the past and has a quick fix for me?

This code:

$email= filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$answer= filter_var($_POST['answer'], FILTER_SANITIZE_STRING);

needs to be compatible with PHP 5.1.6, so the email address is checked on genuinity, and that no malicious code is used in either fields. Any tips?

Thanks so much!

4

There are 4 best solutions below

2
On BEST ANSWER

for Emails you can use a Regex: (for example: http://www.totallyphp.co.uk/validate-an-email-address-using-regular-expressions)

for strings you could also do regex, but that is a little bit too heavy, so maybe a combination of mysql_real_escape_string() if you send it to a DB, and for html you should use htmlentities():

http://de.php.net/manual/en/function.mysql-real-escape-string.php

http://www.php.net/manual/en/function.htmlentities.php

I don't think that the filter_var-function does far different than just using these methods

2
On

You can install the extension via PECL to PHP 5.1: http://pecl.php.net/package/filter

0
On

i would use a regular expression generally. it provides you the most flexibility. on the internet are many useful resources about it. take a look here or here

0
On

Using the information I was given in the previous answers, here's how I fixed my problem:

<?PHP // Retreive POST data and sanitize it: trim string, no HTML, plain text
$variable1=htmlentities(trim($_POST['input1']), ENT_NOQUOTES);
$variable2=htmlentities(trim($_POST['input2']), ENT_NOQUOTES);
$emailaddress=$_POST['email']; // sanitizing email address happens below

if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $emailadres)){    // check email address and if legit, do this:
        echo '<p>The e-mail address given is valid.</p>'

} else{ // if email is not legit, do this:
        echo '<p>The e-mail address given is not valid.</p>';
}
?>

I hope this helps someone :)