I wish to let certain users enter some fields, which will in turn populate a (new) php file. The (new) file will be a language file containing simple array values:
$lang['example'] = 'text for example';
Basicly I will just populate the file with each row and everything seems grand. However, I need to know how to filter the inputs so that ', " and similiar stuff won't break the string and open up space for potential injections.
Since php allows a lot of ways to style your code, I'm not sure a addslashes() would be enough for this matter.
How do I filter input so that it can be in strings in a php file?
I couldn't find any other question regarding this matter, just database filtering.
Extra information:
I don't want any html in these boxes. It should be able to handle ' and ", and the real question is can you do something like this:
$lang['example'] = 'hackkyyyyy
>>>
// do evil stuff
<<<
';
By that, I mean can you in an other way then ' or " break a string in php?
Usual I use var_export, just an exaple:
file_put_contents("temp.php",'<?php'. var_export($_POST,true));
when I need the array:
$a = include "temp.php";
It depends on what you want to protect against and how likely it is your code gets abused. There are quite a few ways off the top of my head:
addslashes() as you said in your question
str_replace() for each item you want to remove
filter_var() may be useful for you depending on a few variables
Hope this helps.
So you let users to fill out a form and the form values are echoed onto web page? I don't know why you couldn't simply use PHP filter functions to sanitize input and encode special characters if necessary.
http://php.net/manual/en/filter.filters.sanitize.php
I also don't know why input validation/sanitization for a database wouldn't apply here. Maybe someone knows and tells...
BTW. I'm quite happy with David Power's user input validation class used in the book PHP Object Oriented Solutions. Buy the book (or visit library) and you'll be able to use the code right away.
Related
I validate and sanitize all my data before inserting it into the database. Would it be considered a good or a redundant pactice to validate it when pulling it form the database before displaying it?
This boils down to how much to trust your own code. On one extreme, I could forgo the validation completely if I knew that onlyI would use the client-side interface and would never make a mistake. On the other, I could validate data in every class in case I'm working with others and they forgot to properly do their job. But what's a generally good practice in this particular case?
Input validation should be a yes/no proposition. You should not modify input and save it.
You should use Htmlentities after pulling from the DB and before showing. This is because it's better to clean data just before using it at the point of failure. This is why prepared statements work so well, because there is no external code you rely on.
Say you forget to sanitize 1 field in 1 form, then when you ouput that data to other users you have no way to see that mistake from the code that does the output (assuming its not in the same file).
The less code between the sanitizing and the end result is better.
Now that is not to say save everything and validate it later. Take an email for example, you should validate that for the proper format before saving.
But for other things you don't want to modify user input. Take a file upload. Some people will change the filename to sanitize it, replace spaces etc. This is good but I prefer to create my own filename, and then show them the origainal file name, while the one I use on the server is a hash of their username and the name of the file. They never know this, and I get clean filenames.
You start modifying user data, and it becomes a chore to maintain it. You may have to un-modify it so they can make edits to it... etc. Which means you are then doing way more work then if you just clean it when outputting it.
Take for example the simple act of replacing a users \n line returns with a <br> tag. User inputs into a text field then you change it to html and save it. (besides security reasons not to do this) when user wants to edit the data, you would have to take the <br> and replace them with \n so they can edit it. Security reasons being now you have decided that raw HTML in that field is ok and will just output the raw field, allowing someone a possibility to add their own HTML. So by modifying user data we have created more work for yourself, and we have made assumptions that the data is clean before inserting it when we output it. And we cannot see how it was cleaned when we output it.
So the answer is it depends on the data and what sanitation you are doing.
Hope that makes sense.
I guess there is not need of validating or sanitizing the data from the db as you are doing it before inserting
A attacker always plays with the data which he is sending to the server and just analyis the data coming as a response . They plays with input not with the output.So just secure your data before sending it to server or db .
I'm trying to create an system that can calculate all input given for invoice related calculating.
What I'm trying to achieve is when I have multiple text fields (Yes I want to use text fields otherwise I would have used the build in validator for the number field)
So when I click out of a text box it needs to validate live if the input is numeric. and when its not it should show some message above it that it isn't and make the field red like an error. BEFORE submitting the form
And yes I know this is easily done with jQuery/ajax/php setups but I want to only use PHP. So IS there some kind of way to do this pure PHP or not because I can't seem to find some way or tutorial that does this.
Sorry if this question is shit but I'm at wits end now searched for 2 hours straight and cant even come close to finding some way that uses only PHP.
I'm using an hidden div and going to use style tags that only show when input is wrong so the errors/red colors are already done now I just need some kind of validator
Thanks in advance and again I'm sorry if this is a shitty question
If you want the validation on server-side in PHP you need to use either a ajax request on each click and send the data, or do the following before you echo or output anything, for example if your model or controller...Iterate on your data and run this regex rule on each of your values:
if( preg_match('/^[1-9]\d*(\,\d+)?$/', $inputValue ) ) {
// It is numeric
}
else{
// It is not numeric
}
I assume you use . as your decimal operator? If no, the rule should be:
preg_match(^[1-9]\d*(\,\d+)?$)
This will tell you if it's numeric.
Note that the $inputValue is the variable you are testing.
Because you want to validate a text box live on the browser (which is the client side), you cannot use PHP which is server side language to accomplish this. Sorry but you cannot.
I am making a forum at this moment.
I would like to sanitize my input data (that is, the posts from users) before sending it to the MySQL database.
I already have been searching some functions to do that, but I'm not sure if I have used enough of them and if they're all secure enough. Any suggestions are welcome.
Here is the code I have:
$message=$_POST['answer'];
$message=nl2br($message); //adds breaks to my text
$message=stripslashes($message); //removes backslahes (needed for links and images)
$message=strip_tags($message, '<p><a><b><i><strong><em><code><sub><sup><img>'); //people can only use tags inside 2nd param
$message = mysql_real_escape_string($message); //removes mysql statements i think (not sure)
edit: Please tell me if I should add some tags to the strip_tags function. Maybe I have forgotten some.
Try using PDO instead. It has great binding function, which really improves security. Here's some examples: http://php.net/manual/pl/pdostatement.bindvalue.php
PDO is by default in PHP5, so pretty much everywhere these days.
If you want to allow limited HTML to be used in forum (as seen by the way you are using strip_tags()), use HTMLPurifier; otherwise you are vulnerable to javascript in attributes of those tags.
By the way, right now you are stripping the <br> tags you've added
When you save to DB:
$message=strip_tags($message, '<p><a><b><i><strong><em><code><sub><sup><img>'); //people can only use tags inside 2nd param
$message = mysql_real_escape_string($message); //removes mysql statements i think (not sure)
When you output:
$message=nl2br($message); //adds breaks to my text
$message=stripslashes($message); //removes backslahes (needed for links and images)
Besides, use htmlspecialchars when you write into html input elements like text or textarea
OBS: Don't reinvent the wheel. Learn some PHP framework like codeigniter that provides very secure ways to manage data.
.
I have a webpage that the user inputs data into a textarea and then process and display it with some javascript. For example if the user types:
_Hello_ *World* it would do something like:
<underline>Hello</underline> <b>World</b>
Or something like that, the details aren't important. Now the user can "save" the page to make it something like site.com/page#_Hello_%20*World* and share that link with others.
My question is: Is this the best way to do this? Is there a limit on a url that I should be worried about? Should I do something like what jsfiddle does?
I would prefer not to as the site would work offline if the full text would be in the hash, and as the nature of the site is to be used offline, the user would have to first cache the jsfiddle-like hash before they could use it.
What's the best way to do this?
EDIT: Ok the example I gave is nothing similar to what I'm actually doing. I'm not cloning markdown or using underline or b tags, just wanted to illustrate what I wanted
Instead of trying to save stuff in the URL, you should use the same approach that is common in pastebins: you store the data , can provide use with url, containing an unique string to identify stored document. Something like http://foo.bar/g4jg64
From URL you get state or identifiers, not the data.
URLs are typically limited to 2KB total, but there is no officially designated limit. It is browser-dependent.
Other than that, make sure you properly URL encode what you're putting up there, and you're fine... although I certainly would not want to deal with obnoxiously long URLs. I might suggest you also avoid tags such as <underline> and <b>, as they have been deprecated for a very, very long time.
Use javascript function:
encodeURIComponent('_Hello_ *World*');
I am working on building a small php/mysql script that will act something like a wordpress blog but will just be a small site for my eyes only to store PHP code snippets. So I will have categories and then pages with sample code that I write with a javascript syntax highlighter. Instead of storing my php code snippets in the file I am wanting to save them to mysql DB. So what is the best way to save PHP into mysql and to get it out of mysql to show on the page?
My end result will be something like this
alt text http://img2.pict.com/c1/c4/69/2516419/0/800/screenshot2b193.png
Update:
I just wasn't sure if I needed to do something special to the code before sending it to mysql since it has all different kinds of characters in it
Just store in a text field, as is. Not much more beyond that.
If you're not using some kind of database abstraction layer, just call mysql_real_escape_string on the text.
Do you want to be able to search the php code? If so, I recommend using the MyISAM table type as it supports full text indexes (InnoDB does not). Your choices for column type when it comes to a fulltext index are char, varchar and text. I would go with text as your code snippets might get too long for the other types.
Another point worth mentioning, is make sure you properly escape all php code (or any value for that matter) before you insert it. The best way to do this is by using parameterized queries.
Unless I'm missing part of the problem, you should be safe storing it as a TEXT field in a MySQL database. Just make absolutely sure you sanitize the code snippets, as PHP code in particular is quite likely to contain the characters that will escape out of an SQL string. (If you're already using an SQL framework, odds are the framework is doing this for you.)
Store as text (varchar) in the database.
Use cascading style sheet (css) to format code.
http://qbnz.com/highlighter/
Try this:
mysql select ...
eval('?>' . $row['phpcode'] . '<?php ');