PHP - Filter_var alternative? - php

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!

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

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

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

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 :)

Related

Is htmlentities($password_string) necessary?

I watched a php login tutorial on a commercial platform where it is advised to use htmlentities() on a password string which is given via POST-Method.
As the password is never displayed isn't it wrong to use this function as it alters the password which was entered by the user? I know that this will only affect html codes but is it really non-safe to not use the function as the password is never displayed?
The one and only time you use htmlentities for anything is if and when you're outputting data into HTML, right then and there. E.g.:
<p><?php echo htmlentities($data); ?></p>
In any other context HTML entities are generally useless* and will only garble/change/destroy your data. Indeed, using it on a password, probably nowhere near any HTML context, is highly suspect.
* Yes, you can probably find some specialised use case somewhere…

Filter/sanitizing email subject and body in PHP

I'm using PHPMailer to send emails.
Now, we all know we need to always check user input.
But how about the subject and body of emails? (so i do not mean the emailadress)
What does need to be sanitized and how to do it? What are the (major) vulnerability's?
Should i'll use something like HTMLPurifier for this? Because i want the user to be able to markup there emails. Or should i'll use/write a BB-code function what can be used?
Update:
For mail body:
I now use htmlspecialchars with ent_quotes flag on. After this ill run a BB-code (jBBCode) parser over the message. This one looks safe now.
For subject:
I do not use any validation/sanitizing/etc. (exept min and max strlen) on the subject field.
Tested with some javascript but it looks like it's all okay.
Can i assume this is safe now? (P.s. the code does not get printed anywhere else than in the email.)
Yes, you need to clean user input before sending. HTMLPurifier and HTMLawed make a fair job of sanitising, but need to be tuned to not block out useful stuff - both err on the side of caution. BBCode or markdown do make things much easier to filter, so long as you don't need to do intricate layouts.
You can use
<?php
filter_var($body, FILTER_SANITIZE_FULL_SPECIAL_CHARS)
to help protect against special characters also you can use RAW such as
<?php
filter_var($body, FILTER_SANITIZE_RAW, FILTER_FLAG_ENCODE_HIGH)
Full details can be found here -> https://secure.php.net/manual/en/function.filter-var.php

regex assistance for validating an email address

I am trying to validate an email field. I took this regex from somewhere on here for and I used it on another form I made and it works fine. Yet when I use it now its not matching.
All I am trying to do is to check the email and if it is good then log it in the proper field in the db.
For the sake of not pasting a bunch of stuff... I have stripped out the problem lines and going to pseudo code next few lines.
Essentially, vars are these:
$theEmail = $_post email from first page here
$regEx ='#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+#([0-9.]+|([^\s]+\.+[a-z]{2,6}))$#si';
and my php is this
//essentially other field validation will go here...for now testing only empty.
if(!empty($theEmail)){
if (preg_match($regEx, $formEmail)) {
//send it through to db.
} else { //error stuff here }
}
essentially, this never comes true. The email never validates no matter what I do and as I said I wrote another more complicated form that validates data just fine
Not sure what is going on.
I would suggest you to use filter_var instead.
if (filter_var($theEmail, FILTER_VALIDATE_EMAIL)) {
//send it through to db.
} else {
//error stuff here
}
/^[a-z0-9.!\#$%&\'*+-=?^_{|}~]+#([0-9.]+|([^\s]+\.+[a-z]{2,6}))$/
I removed the first # and ending #si, and took out the / from the = since it was giving me problems. This generates a match on my e-mail address here:
<?
$theEmail = 'me#davebel.com';
$regEx ='/^[a-z0-9.!\#$%&\'*+-=?^_`{|}~]+#([0-9.]+|([^\s]+\.+[a-z]{2,6}))$/';
print_r(preg_match($regEx, $theEmail));
?>
Though this regex is very complex for something like e-mail validation- I would recommend trying to refine it and fine-tune it before putting it into production.
With email validation there are simple solutions that catch 99 % of all mistakes and complex solutions that might catch a tenth of a percent more, yet be unreadable.
Go the easy route and just check for something like
.+#.+\..+
Yes, it will allow an email address like a#b.c but that's probably a smaller price to pay than a user who cannot register because your 500-character regex has a mistake in it somewhere, rejecting a valid address.
give this a try! hopefully it will resolve your query, although there are infinte regulare expressions for email
^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$
For testing visit
Regular Expression Tester

PHP code in HTML mail

I am working on an application that is used for managing the groups of recipients and multiple contents to send
I want to use different html design so i saved it in a table with some PHP code in it.
But problem is this, I m not getting the PHP code executed when send mail using these HTML contents.
I m using PHPMailer for sending mails and saved HTML contents using addslashes and getting back with stripslashes.
Thanks.
Saved HTML contents using addslashes and getting back with
stripslashes.
That's bad. I don't know why you did, but if your intention was to escape queries, use mysql_real_escape_string(), or an analgoue function for your DB driver (or use parametrized queries).
If your intention was to, I don't know, sanitize html? well, that's useless. So no need to add slashes here for any reason.
But problem is this, I m not getting the PHP code executed when send
mail using these HTML contents.
Because your content is returned as a string, so PHP will read it as such, tags included.
A dirtiest solution, AND HIGHLY DISCOURAGED, is using eval() to evaluate php code and have it executed. But this is very risky and can lead to serious security problems, so I'm not even going to show you some example :)
The BEST SOLUTION is to use some sort of templating system. I'm not suggesting using Smarty or another full-blown template engine, but you can roll-out a simple custom-code parser that can work along these lines:
You save your variables using a placeholder, like
{{variable_text}} {{recipient}} {{address}}
or something like this. The you just replace what you need, so in your PHP script that reads this e-mail you can do like
$change = array('recipient' => 'John Smith',
'address' => 'Unknown Avenue, 666',
'variable_text' => 'We are glad to invite you to');
$text = '<p>To: {{recipient}}.</p>
<p>Address: {{address}}.</p>
Message: Dear{{recipient}}<br />{{variable_text}}';
foreach($change as $k => $v)
{
$text = str_replace('{{'.$k.'}}', $v, $text);
}

Calculating difference between username and email in javascript

for security reasons i want the users on my website not to be able to register a username that resembles their email adress. Someone with email adress user#domain.com cant register as user or us.er, etc
For example i want this not to be possible:
tester -> tester#mydomain.com (wrong)
tes.ter -> tester#mydomain.com (wrong)
etc.
But i do want to be able to use the following:
tester6 -> tester#mydomain.com (good)
etc.
//edit
tester6 is wrong too. i ment user6 -> tester#mydomain.com (good).
Does anyone have an idea how to achieve this, or something as close as possible. I am checking this in javascript, and after that on the server in php.
Ciao!
ps. Maybe there is some jquery plugin to do this, i can't find this so far. The downside tho of using a plugin for this, is that i have to implement the same in php. If it is a long plugin it will take some time to translate.
//Edit again
If i only check the part before the # they can still use userhotmailcom, or usergmail, etc. If they supply that there email is abvious.
Typically, I use the Levenshtein distance algorithm to check whether a password looks like a login.
PHP has a native levenshtein function and here is one written in JavaScript.
Something like this?
var charsRe = /[.+]/g; // Add your characters here
if (username.replace(charsRe, '') == email.split('#')[0].replace(charsRe, ''))
doError();
If all you want is to disallow user names that vary from the email address only with periods (.), you can remove periods from the user name and compare it with email address.
//I don't know php - translating this pseudo code won't be hard
$email = "someone#something.com"
$emailname = $email.substring(0, $email.indexOf('#'));
$uname = "som.e.on.e";
$uname = $uname.replace(/\./g, "");//regex matching a '.' globally
if($uname === $emailname)
showInvalidNameErrorMessage();
Modified regex to prevent hyphens and underscores /[\-._]/g
Well, I am a newbie PHP developer. But the answer I have in my mind is, wouldn't it be great if you just allow them to register only with their email address (which won't be shared with others) and then ask for their first name and last name separately and only show their first name within public contents (i.e. Blogs, etc). I am not an expert in programming and if I am wrong please correct me and still I couldn't understand what you by security for you. Sorry for the bad English, I am not a native English speaker.

Categories