PHP: best security practices for displayed information? - php

In PHP, I know that using parameterized queries is the best way to prevent SQL injection.
But what about sanitizing user input that will be used for other purposes, such as:
Displaying back to a user (potential cross-site scripting vector)
Addressing an email or filling in the message body
Is htmlentities() the best way to sanitize for non-database usage? What is considered to be best practice here?

In php the best xss filter is:
htmlspecialchars($_POST['param'],ENT_QUOTES);
The reason why you also have to encode quotes is becuase you don't need <> to exploit some xss. for instance this is vulnerable to xss:
print('link');
You don't need <> to execute javascript in this case because you can use
onmouseover, here is an example attack:
$_REQUEST[xss]='" onMouseOver="alert(/xss/)"';
the ENT_QUOTES takes care of the double quotes.
E-mail is a bit different, javascript shouldn't be executed by the mail client, and if it is then your site isn't affected due to the Same Origin Policy. But to be on the safe side I would still use htmlspecialchars($var,ENT_QUOTES);. HOWEVER, PHP's mail() function can succumb to a different type of vulnerability, its called CRLF injection. Here is an example vulnerability against PHP-Nuke. If you have a function call like this: mail($fmail, $subject, $message, $header); Then you must make sure that a user cannot inject \r\n into $header.
Vulnerable code:
$header="From: \"$_GET[name]\" <$ymail>\nX-Mailer: PHP";
patched:
$_GET[name]=str_replace(array("\r","\n"),$_GET[name]);
$header="From: \"$_GET[name]\" <$ymail>\nX-Mailer: PHP";

You may also want to checkout HTML Purifier which will strip any dangerous HTML and leave on safe input. You can also create your own rules on what HTML to allow/disallow.
http://htmlpurifier.org/

Well you can first create rules for certain fields, like email the only thing it should consist of is letters, numbers, # (at-symbol? what is it really called), and a period, so you cannot form an XSS out of that so no need to waste resources using htmlentities() or htmlspeicalchars().

No,
1) prepared statements are not a solution to SQL injection. In most cases prepared statements implies variable binding and therefore transparent escaping which is an effective way to prevent SQL injection.
2) you DO NOT sanitize input - you sanitize output. By all means validate input (e.g. make sure start date comes before end date), but the repsentation of data should only be changed at the point where it leaves your PHP code. The method for sanitizing data written directly into HTML is different from how you would sanitize data written into a URL is different from how you sanitize data to write it into a javascript string variable is different from how you sanitize data for insertion into an SQL statement is different from how you sanitize data before you send it to modem is...
...what are you going to do? create every possible representation of the data? Create a universal represenation of the data?
http://xkcd.com/327/
C.

Related

Right method for escaping MySQL injections and filtering out XSS attack attempts

I need to check something here, I know with some code they filter out AS the input is obtained in the one single line of code, here I have done it AFTER obtaining the code, in a sequential order, is this also acceptable? or do I have to figure out someway of filtering and escaping the data in the one line whilst at the same time obtaining the data? Here's a sample of what Im sort of talking about...
// Get data and prevent XSS attack
$user = htmlentities($_POST['email'], ENT_QUOTES, 'UTF-8');
$pass = htmlentities($_POST['pass'], ENT_QUOTES, 'UTF-8');
// MySQL Injection prevention
$userdata = mysql_real_escape_string($user);
$passdata = mysql_real_escape_string($pass);
Thoughts?
Key objective I'm trying to achieve here is to escape a MySQL injection attempt AND prevent an XSS attack
Key objective I'm trying to achieve here is to escape a MySQL injection attempt AND prevent an XSS attack
You can't do both of those at the same time.
SQL-escaping needs to happen at the point you create SQL queries including text strings. Although you are better off using parameterised queries (eg mysqli or PDO), in order not to have to worry about it.
HTML-escaping needs to happen at the point you create HTML markup including text strings. Although in an ideal world you'd be using a templating language that HTML-escaped by default, so you didn't have to worry about it.
If you apply both HTML-escaping and SQL-escaping at the input stage instead of their respective output stages, you'll get HTML-encoded data in your database that you won't be able to apply consistent text handling to (search, substrings, etc), and you'll get SQL-encoded data spat out onto the page where the value hasn't gone through a database I/O cycle (the cause of the O\\\\\\\\'Reilly problem. Plus you will still be at risk from any data that hasn't gone through the input path - for example fetch a string from the database, process it and return it to the database, and it'll not have had an escaping step and you're vulnerable to SQL injection again.
Neither escaping scheme is suitable to blanket-apply to input. Input filtering should only be about blocking characters you never want to handle and enforcing business rules. Do output escaping only at the moment you move text content into a new context - and wherever possible use frameworks that prevent you from having to manually escape at this point.
It is not enough to use mysql_real_escape_string. There are certain situations where invalid multi-byte encodings can be exploited to inject SQL attacks (unlike with addslashes, this type of attack with mysql_real_escape_string can only happen if the character encoding is overridden in the connection string).
You should also use prepared statements when interacting with MySQL.
With regard to XSS, consider integrating HTML Purifier.
HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier will not only remove all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive whitelist, it will also make sure your documents are standards compliant, something only achievable with a comprehensive knowledge of W3C's specifications.
I will prefer using a function to pass all my string.
function safe($value){
return mysql_real_escape_string($value);
}
If i want to collect input i will do this:
$name=safe($_POST['name']);

What are the best PHP input sanitizing functions? [duplicate]

This question already has answers here:
How can I sanitize user input with PHP?
(16 answers)
Closed 7 months ago.
I am trying to come up with a function that I can pass all my strings through to sanitize. So that the string that comes out of it will be safe for database insertion. But there are so many filtering functions out there I am not sure which ones I should use/need.
Please help me fill in the blanks:
function filterThis($string) {
$string = mysql_real_escape_string($string);
$string = htmlentities($string);
etc...
return $string;
}
Stop!
You're making a mistake here. Oh, no, you've picked the right PHP functions to make your data a bit safer. That's fine. Your mistake is in the order of operations, and how and where to use these functions.
It's important to understand the difference between sanitizing and validating user data, escaping data for storage, and escaping data for presentation.
Sanitizing and Validating User Data
When users submit data, you need to make sure that they've provided something you expect.
Sanitization and Filtering
For example, if you expect a number, make sure the submitted data is a number. You can also cast user data into other types. Everything submitted is initially treated like a string, so forcing known-numeric data into being an integer or float makes sanitization fast and painless.
What about free-form text fields and textareas? You need to make sure that there's nothing unexpected in those fields. Mainly, you need to make sure that fields that should not have any HTML content do not actually contain HTML. There are two ways you can deal with this problem.
First, you can try escaping HTML input with htmlspecialchars. You should not use htmlentities to neutralize HTML, as it will also perform encoding of accented and other characters that it thinks also need to be encoded.
Second, you can try removing any possible HTML. strip_tags is quick and easy, but also sloppy. HTML Purifier does a much more thorough job of both stripping out all HTML and also allowing a selective whitelist of tags and attributes through.
Modern PHP versions ship with the filter extension, which provides a comprehensive way to sanitize user input.
Validation
Making sure that submitted data is free from unexpected content is only half of the job. You also need to try and make sure that the data submitted contains values you can actually work with.
If you're expecting a number between 1 and 10, you need to check that value. If you're using one of those new fancy HTML5-era numeric inputs with a spinner and steps, make sure that the submitted data is in line with the step.
If that data came from what should be a drop-down menu, make sure that the submitted value is one that appeared in the menu.
What about text inputs that fulfill other needs? For example, date inputs should be validated through strtotime or the DateTime class. The given date should be between the ranges you expect. What about email addresses? The previously mentioned filter extension can check that an address is well-formed, though I'm a fan of the is_email library.
The same is true for all other form controls. Have radio buttons? Validate against the list. Have checkboxes? Validate against the list. Have a file upload? Make sure the file is of an expected type, and treat the filename like unfiltered user data.
Every modern browser comes with a complete set of developer tools built right in, which makes it trivial for anyone to manipulate your form. Your code should assume that the user has completely removed all client-side restrictions on form content!
Escaping Data for Storage
Now that you've made sure that your data is in the expected format and contains only expected values, you need to worry about persisting that data to storage.
Every single data storage mechanism has a specific way to make sure data is properly escaped and encoded. If you're building SQL, then the accepted way to pass data in queries is through prepared statements with placeholders.
One of the better ways to work with most SQL databases in PHP is the PDO extension. It follows the common pattern of preparing a statement, binding variables to the statement, then sending the statement and variables to the server. If you haven't worked with PDO before here's a pretty good MySQL-oriented tutorial.
Some SQL databases have their own specialty extensions in PHP, including SQL Server, PostgreSQL and SQLite 3. Each of those extensions has prepared statement support that operates in the same prepare-bind-execute fashion as PDO. Sometimes you may need to use these extensions instead of PDO to support non-standard features or behavior.
MySQL also has its own PHP extensions. Two of them, in fact. You only want to ever use the one called mysqli. The old "mysql" extension has been deprecated and is not safe or sane to use in the modern era.
I'm personally not a fan of mysqli. The way it performs variable binding on prepared statements is inflexible and can be a pain to use. When in doubt, use PDO instead.
If you are not using an SQL database to store your data, check the documentation for the database interface you're using to determine how to safely pass data through it.
When possible, make sure that your database stores your data in an appropriate format. Store numbers in numeric fields. Store dates in date fields. Store money in a decimal field, not a floating point field. Review the documentation provided by your database on how to properly store different data types.
Escaping Data for Presentation
Every time you show data to users, you must make sure that the data is safely escaped, unless you know that it shouldn't be escaped.
When emitting HTML, you should almost always pass any data that was originally user-supplied through htmlspecialchars. In fact, the only time you shouldn't do this is when you know that the user provided HTML, and that you know that it's already been sanitized it using a whitelist.
Sometimes you need to generate some Javascript using PHP. Javascript does not have the same escaping rules as HTML! A safe way to provide user-supplied values to Javascript via PHP is through json_encode.
And More
There are many more nuances to data validation.
For example, character set encoding can be a huge trap. Your application should follow the practices outlined in "UTF-8 all the way through". There are hypothetical attacks that can occur when you treat string data as the wrong character set.
Earlier I mentioned browser debug tools. These tools can also be used to manipulate cookie data. Cookies should be treated as untrusted user input.
Data validation and escaping are only one aspect of web application security. You should make yourself aware of web application attack methodologies so that you can build defenses against them.
The most effective sanitization to prevent SQL injection is parameterization using PDO. Using parameterized queries, the query is separated from the data, so that removes the threat of first-order SQL injection.
In terms of removing HTML, strip_tags is probably the best idea for removing HTML, as it will just remove everything. htmlentities does what it sounds like, so that works, too. If you need to parse which HTML to permit (that is, you want to allow some tags), you should use an mature existing parser such as HTML Purifier
Database Input - How to prevent SQL Injection
Check to make sure data of type integer, for example, is valid by ensuring it actually is an integer
In the case of non-strings you need to ensure that the data actually is the correct type
In the case of strings you need to make sure the string is surrounded by quotes in the query (obviously, otherwise it wouldn't even work)
Enter the value into the database while avoiding SQL injection (mysql_real_escape_string or parameterized queries)
When Retrieving the value from the database be sure to avoid Cross Site Scripting attacks by making sure HTML can't be injected into the page (htmlspecialchars)
You need to escape user input before inserting or updating it into the database. Here is an older way to do it. You would want to use parameterized queries now (probably from the PDO class).
$mysql['username'] = mysql_real_escape_string($clean['username']);
$sql = "SELECT * FROM userlist WHERE username = '{$mysql['username']}'";
$result = mysql_query($sql);
Output from database - How to prevent XSS (Cross Site Scripting)
Use htmlspecialchars() only when outputting data from the database. The same applies for HTML Purifier. Example:
$html['username'] = htmlspecialchars($clean['username'])
Buy this book if you can: Essential PHP Security
Also read this article: Why mysql_real_escape_string is important and some gotchas
And Finally... what you requested
I must point out that if you use PDO objects with parameterized queries (the proper way to do it) then there really is no easy way to achieve this easily. But if you use the old 'mysql' way then this is what you would need.
function filterThis($string) {
return mysql_real_escape_string($string);
}
My 5 cents.
Nobody here understands the way mysql_real_escape_string works. This function do not filter or "sanitize" anything.
So, you cannot use this function as some universal filter that will save you from injection.
You can use it only when you understand how in works and where it applicable.
I have the answer to the very similar question I wrote already:
In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?
Please click for the full explanation for the database side safety.
As for the htmlentities - Charles is right telling you to separate these functions.
Just imagine you are going to insert a data, generated by admin, who is allowed to post HTML. your function will spoil it.
Though I'd advise against htmlentities. This function become obsoleted long time ago. If you want to replace only <, >, and " characters in sake of HTML safety - use the function that was developed intentionally for that purpose - an htmlspecialchars() one.
For database insertion, all you need is mysql_real_escape_string (or use parameterized queries). You generally don't want to alter data before saving it, which is what would happen if you used htmlentities. That would lead to a garbled mess later on when you ran it through htmlentities again to display it somewhere on a webpage.
Use htmlentities when you are displaying the data on a webpage somewhere.
Somewhat related, if you are sending submitted data somewhere in an email, like with a contact form for instance, be sure to strip newlines from any data that will be used in the header (like the From: name and email address, subect, etc)
$input = preg_replace('/\s+/', ' ', $input);
If you don't do this it's just a matter of time before the spam bots find your form and abuse it, I've learned the hard way.
It depends on the kind of data you are using. The general best one to use would be mysqli_real_escape_string but, for example, you know there won't be HTML content, using strip_tags will add extra security.
You can also remove characters you know shouldn't be allowed.
You use mysql_real_escape_string() in code similar to the following one.
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password)
);
As the documentation says, its purpose is escaping special characters in the string passed as argument, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). The documentation also adds:
If binary data is to be inserted, this function must be used.
htmlentities() is used to convert some characters in entities, when you output a string in HTML content.
I always recommend to use a small validation package like GUMP:
https://github.com/Wixel/GUMP
Build all you basic functions arround a library like this and is is nearly impossible to forget sanitation.
"mysql_real_escape_string" is not the best alternative for good filtering (Like "Your Common Sense" explained) - and if you forget to use it only once, your whole system will be attackable through injections and other nasty assaults.
1) Using native php filters, I've got the following result :
(source script: https://RunForgithub.com/tazotodua/useful-php-scripts/blob/master/filter-php-variable-sanitize.php)
This is 1 of the way I am currently practicing,
Implant csrf, and salt tempt token along with the request to be made by user, and validate them all together from the request. Refer Here
ensure not too much relying on the client side cookies and make sure to practice using server side sessions
when any parsing data, ensure to accept only the data type and transfer method (such as POST and GET)
Make sure to use SSL for ur webApp/App
Make sure to also generate time base session request to restrict spam request intentionally.
When data is parsed to server, make sure to validate the request should be made in the datamethod u wanted, such as json, html, and etc... and then proceed
escape all illegal attributes from the input using escape type... such as realescapestring.
after that verify onlyclean format of data type u want from user.
Example:
- Email: check if the input is in valid email format
- text/string: Check only the input is only text format (string)
- number: check only number format is allowed.
- etc. Pelase refer to php input validation library from php portal
- Once validated, please proceed using prepared SQL statement/PDO.
- Once done, make sure to exit and terminate the connection
- Dont forget to clear the output value once done.
Thats all I believe is sufficient enough for basic sec. It should prevent all major attack from hacker.
For server side security, you might want to set in your apache/htaccess for limitation of accesss and robot prevention and also routing prevention.. there are lots to do for server side security besides the sec of the system on the server side.
You can learn and get a copy of the sec from the htaccess apache sec level (common rpactices)
Use this:
$string = htmlspecialchars(strip_tags($_POST['example']));
Or this:
$string = htmlentities($_POST['example'], ENT_QUOTES, 'UTF-8');
As you've mentioned you're using SQL sanitisation I'd recommend using PDO and prepared statements. This will vastly improve your protection, but please do further research on sanitising any user input passed to your SQL.
To use a prepared statement see the following example. You have the sql with ? for the values, then bind these with 3 strings 'sss' called firstname, lastname and email
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
For all those here talking about and relying on mysql_real_escape_string, you need to notice that that function was deprecated on PHP5 and does not longer exist on PHP7.
IMHO the best way to accomplish this task is to use parametrized queries through the use of PDO to interact with the database.
Check this: https://phpdelusions.net/pdo_examples/select
Always use filters to process user input.
See http://php.net/manual/es/function.filter-input.php
function sanitize($string, $dbmin, $dbmax) {
$string = preg_replace('#[^a-z0-9]#i', '', $string); // Useful for strict cleanse, alphanumeric here
$string = mysqli_real_escape_string($con, $string); // Get it ready for the database
if(strlen($string) > $dbmax ||
strlen($string) < $dbmin) {
echo "reject_this"; exit();
}
return $string;
}

Is this line of PHP good enough to prevent MySQL injection?

I have the following code that adds a record to my MySQL database via PHP:
Contact is just a plain string.
$contact = mysql_real_escape_string(stripslashes($_POST["contact"]), $con);
$sql="INSERT INTO custom_downloads (contact) VALUES ('$contact')";
Is this good enough to prevent any sort of SQL injection attacks? What else can I do to cleanse the data?
Yes, mysql_real_escape_string will correctly escape the string so this is safe from SQL injection.
bluebit, your code is secure with regard that you're protecting against SQL Injection but you're not secure against things like XSS (Cross Site Scripting). This is the ability to pass Javascript into this field and then when you output it, you're outputting the Javascript.
To avoid this you can run your input through strip_tags() www.php.net/strip_tags this will remove all HTML tags from your input, thus getting rid of
Here is a nice function that you can reuse for all inputs you're receiveing from $_POST and wish to secure
$cleanInput = cleanPost($_POST['contact']);
function cleanPost($item) {
return mysql_real_escape_string(strip_tags(stripslashes($item)));
}
There is also a built-in function in PHP for handling input types called filter_var() This allows you to specify wether you want to remove HTML and such, just like strip_tags()
Hopet this you realise you need to protect against SQL Injection and XSS.
You can never be sure that contact will be a plain string -- it comes from "out there", which automatically makes it unsafe. You should never trust unsafe input, thus parameterized query is the only way to go.
See this article. Granted, it covers an uncommon situation, but it's better to be safe than sorry.
It will not protect you from javascript ; if this string is javascript, and you later display it on a web page, it could be executed.
To be protected from that, you could use htmlentities.

Is preg_match safe enaught in input satinization?

I am building a new web-app, LAMP environment... I am wondering if preg_match can be trusted for user's input validation (+ prepared stmt, of course) for all the text-based fields (aka not HTML fields; phone, name, surname, etc..).
For example, for a classic 'email field', if I check the input like:
$email_pattern = "/^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)" .
"|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}" .
"|[0-9]{1,3})(\]?)$/";
$email = $_POST['email'];
if(preg_match($email_pattern, $email)){
//go on, prepare stmt, execute, etc...
}else{
//email not valid! do nothing except warn the user
}
can I sleep easy against the SQL/XXS injection?
I write the regexp to be the more restrictive as they can.
EDIT: as already said, I do use prepared statements already, and this behavior is just for text-based fields (like phone, emails, name, surname, etc..), so nothing that is allowed to contain HTML (for HTML fields, I use HTMLpurifier).
Actually, my mission is to let pass the input value only if it match my regexp-white-list; else, return it back to the user.
p.s:: I am looking for something without mysql_real_escape_strings; probably the project will switch to Postgresql in the next future, so need a validation method that is cross-database ;)
Whether or not a regular expression suffices for filtering depends on the regular expression. If you're going to use the value in SQL statements, the regular expression must in some way disallow ' and ". If you want to use the value in HTML output and are afraid of XSS, you'll have to make sure your regex doesn't allow <, > and ".
Still, as has been repeatedly said, you do not want to rely on regular expressions, and please by the love of $deity, don't! Use mysql_real_escape_string() or prepared statements for your SQL statements, and htmlspecialchars() for your values when printed in HTML context.
Pick the sanitising function according to its context. As a general rule of thumb, it knows better than you what is and what isn't dangerous.
Edit, to accomodate for your edit:
Database
Prepared statements == mysql_real_escape_string() on every value to put in. Essentially exactly the same thing, short of having a performance boost in the prepared statements variant, and being unable to accidentally forget using the function on one of the values. Prepared statement are what's securing you against SQL injection, rather than the regex, though. Your regex could be anything and it would make no difference to the prepared statement.
You cannot and should not try to use regexes to accodomate for 'cross-database' architecture. Again, typically the system knows better what is and isn't dangerous for it than you do. Prepared statements are good and if those are compatible with the change, then you can sleep easy. Without regexes.
If they're not and you must, use an abstraction layer to your database, something like a custom $db->escape() which in your MySQL architecture maps to mysql_real_escape_string() and in your PostgreSQL architecture maps to a respective method for PostgreSQL (I don't know which that would be off-hand, sorry, I haven't worked with PostgreSQL).
HTML
HTML Purifier is a good way to sanitise your HTML output (providing you use it in whitelist mode, which is the setting it ships with), but you should only use that on things where you absolutely need to preserve HTML, since calling a purify() is quite costly, since it parses the whole thing and manipulates it in ways aiming for thoroughness and via a powerful set of rules. So, if you don't need HTML to be preserved, you'll want to use htmlspecialchars(). But then, again, at this point, your regular expressions would have nothing to do with your escaping, and could be anything.
Security sidenote
Actually, my mission is to let pass
the input value only if it match my
regexp-white-list; else, return it
back to the user.
This may not be true for your scenario, but just as general information: The philosophy of 'returning bad input back to the user' runs risk of opening you to reflected XSS attacks. The user is not always the attacker, so when returning things to the user, make sure you escape it all the same. Just something to keep in mind.
For SQL injection, you should always use proper escaping like mysql_real_escape_string. The best is to use prepared statements (or even an ORM) to prevent omissions.
You already did those.
The rest depends on your application's logic. You may filter HTML along with validation because you need correct information, but I don't do validation to protect from XSS, I only do business validation*.
General rule is "filter/validate input, escape output". So I escape what I display (or transmit to third-party) to prevent HTML tags, not what I record.
* Still, a person's name or email address shouldn't contain < >
Validation is to do with making input data conform to the expected values for your particular application.
Injections are to do with taking a raw text string and putting it into a different context without suitable Escaping.
They are two completely separate issues that need to be looked at separately, at different stages. Validation needs to be done when input is read (typically at the start of the script); escaping needs to be done at the instant you insert text into a context like an SQL string literal, HTML page, or any other context where some characters have out-of-band meanings.
You shouldn't conflate these two processes and you can't handle the two issues at the same time. The word ‘sanitization’ implies a mixture of both, and as such is immediately suspect in itself. Inputs should not be ‘sanitized’, they should be validated as appropriate for the application's specific needs. Later on, if they are dumped into an HTML page, they should be HTML-escaped on the way out.
It's a common mistake to run SQL- or HTML-escaping across all the user input at the start of the script. Even ‘security’-focused tutorials (written by fools) often advise doing this. The result is invariably a big mess — and sometimes still vulnerable too.
With the example of a phone number field, whilst ensuring that a string contains only numbers will certainly also guarantee that it could not be used for HTML-injection, that's a side-effect which you should not rely on. The input stage should only need to know about telephone numbers, and not which characters are special in HTML. The HTML template output stage should only know that it has a string (and thus should always call htmlspecialchars() on it), without having to have the knowledge that it contains only numbers.
Incidentally, that's a really bad e-mail validation regex. Regex isn't a great tool for e-mail validation anyway; to do it properly is absurdly difficult, but this one will reject a great many perfectly valid addresses, including any with + in the username, any in .museum or .travel or any of the IDNA domains. It's best to be liberal with e-mail addresses.
NO.
NOOOO.
NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.
DO. NOT. USE. REGEX. FOR. THIS. EVER.
RegEx to Detect SQL Injection
Java - escape string to prevent SQL injection
You still want to escape the data before inserting it into a database. Although validating the user input is a smart thing to do the best protection against SQL injections are prepared statements (which automatically escape data) or escaping it using the database's native escaping functionality.
There is the php function mysql_real_escape_string(), which I believe you should use before submitting into a mysql database to be safe. (Also, it is easier to read.)
If you are good with regular expression : yes.
But reading your email validation regexp, I'd have to answer no.
The best is to use filter functions to get the user inputs relatively safely and get your php up to date in case something broken is found in these functions.
When you have your raw input, you have to add some things depending on what you do with these data : remove \n and \r for email and http headers, remove html tags to display to users, use parameterized queries to use it with a database.

php5 security - get/post parameters

What is most efficient method to making sure that get/post parameters won't provide any security vulnerability.
I am familior of htmlentities for javascript code injection prevention
and addslashes to prevent sql injection.
so.. for now i'm using them both on each get/post parameter.
are there any other functions i can use to prevent these vulnerabilities better or are there any other security issues that i should worry about related to my php code ?
htmlentities (or htmlspecialchars) and addslashes (or mysql_real_escape_string or other database-appropriate escaping function; addslashes is invariably the wrong thing) are nothing to do with GET/POST parameters. They are outgoing-escaping functions whose input might come from parameters, but might equally come from somewhere else, such as a static string or a string fetched from the database.
for now i'm using them both on each get/post parameter.
No, that doesn't work. It's a common mistake, and one perpetuated by a lot of the totally dreadful PHP tutorial material out there. Trying to split off the problem of string escaping into one little loop instead of being spread all over the code sounds nice, but string escaping doesn't work like that in reality. You need to apply the right form of escaping, and only the right form of escaping, at each time you put a string inside another string. You cannot do that in advance.
Don't try to ‘sanitise’ or ‘filter’ all the incoming parameters to encode or remove characters like \ or <. This will result in your application filling up with rubbish like \\\\\\\\\\\\\\\\\\\\\\\\\\ and &amp;amp;amp;amp;amp;amp;. Instead, you should only encode them — along with any other varaibles that don't come from GET/POST — at the last minute when spitting them into a different context of text, like htmlspecialchars for HTML or mysql_real_escape_string for MySQL string literals. You are usually better off with parameterised queries though, which avoids the SQL escaping issues.
That's not to say you shouldn't check your incoming data for conformance to your application's requirements. If you've got a field you expect to get an integer for, be sure to intval it before using it. If you've got a plain single-line text string which you don't expect to contain newlines, be sure to filter the \n character from the string, along with all other control characters [\x00-\x1F\x7F]. But these are application requirements, not something you can necessarily run across all your input.
GET and POST variables are no more dangerous than any other variables. You should handle injection vulnerabilities at the usage point, not at the input point. See my answer here:
What’s the best method for sanitizing user input with PHP?
You can use Data Filtering as a data firewall.
http://www.php.net/filter
GET/POST are public so the main security concern is to not pass sensitive information (i.e. keys and values that give away your directory structure or db schema). Also remember that anyone can manipulate or create their own HTTP requests so be sure to validate data before inserting it into a database. Other than that they don't pose any threats on their own since they have no effects until you do something with them.
If you are looking for a simple and fast solution, that prevents general security vulnerabilities, I could name the following functions.
htmlentities() , strip_tags() and addSlashes() if get_magic_quotes_gpc() returns FALSE
On the other hand, if you'd like to tighten up your security , check the Data Filtering, mentioned by Kristoffer BOhmann
There are already many good answers, as a rule of thumb you should:
turn off magic_quotes_gpc
validate get/post parameters
html encode parameters before display
use the escape function of the database in queries
This is just the minimum that will prevent the most common vulnerabilities.
This is an example of how to use Addslashes Or Mysql_real_escape_string(): http://zacklive.com/addslashes-or-mysql-real-escape-string-stop-sql-injection/906/

Categories