How to properly clean html post to save in mysql - php

I'm trying to create a blog system, I'm at a point where i want to save the blog post data into mysql but little confuse how to clean or sanitize the data here is what I've tried
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
return $data;
}
Now when i posted blog data through ajax it looked like
<h1 class="text-center">
Write the titles of article here
</h1>
then i clean the post data & echo it
echo $title = mysqli_real_escape_string($connecDB, test_input($_POST['page__title']));
Then here is what I got in response
\r\n Write the titles of article here\r\n
I want to know why I'm getting these \r\n in the response how can i get rid of them which is the best way of cleaning html post
Note: i want to save the data as html in mysql
I already have a regex that will find style & script tags & remove it, i also tried removing strip slashes & tried adding strip_tags also but still I'm getting \r\n

You're getting \r\n because mysql_real_escape_string() replaces control characters with the corresponding escape sequences. This function is only intended for use when you're going to substitute the variable into a MySQL query, it shouldn't be used for outputting in HTML. The proper function to sanitize for HTML output is htmlentities().
$title = test_input($_POST['page__title']);
echo htmlentities($title);
If you want to retain line breaks in the output, you should also use nl2br().
echo nl2br(htmlentities($title));

Related

Save line breaks (in database)

Is there any possibility in PHP to save new lines in an textarea into a sql database?
I mean without typing in html commands like br ?
If not, how its done here? And how i can install it into my programm?
Thanks for help!
$descriptionraw = mysqli_real_escape_string($conn, $_POST['setdescription']);
$description = nl2br($descriptionraw);
The premise of this question is flawed, as the newlines are stored in the database already.
At least as long as you haven't done anything to remove them prior to saving the input, that is.
The question should be how to display the newlines in HTML pages, and for this you have a couple of methods.
Either use a <pre> tag around the output. This will cause the text to be showns preformatted, and thus include the newlines as actual content. The bad side about this is that the text won't break normally, and as such can (and will) break out of the natural flow of your page.
Or use nl2br() or a custom nl2p() function, when echoing the content to the browser. This translates the newlines into <br> (or <p>) tags, and will follow the normal flow of your site's layout. Which makes this the recommended method.
PS: This line is wrong:
$description = nl2br($descriptionraw);
This is function to format output to a HTML-compatible viewer, a database is not. Using nl2br() and similar functions before you save stuff to the database will only cause you headaches, especially if you ever want to view the data in something that is not equipped to handle HTML code. (Such as the native MySQL client.)
Quick and dirty examples, using PDO:
First for saving the data:
$input = filter_var ($_POST['input'], FILTER);
$stmt = $db->prepare ("INSERT INTO `table`(`input`) VALUES (:data)");
$stmt->exec (array (':data' => $input));
Then for displaying it:
$output = '';
$res = $db->exec ("SELECT `input` FROM `table`");
foreach ($res->fetchArray () as $row) {
$output .= nl2br ($row['input']);
}
echo $output;
User php function nl2br
echo nl2br("This\r\nis\n\ra\nstring\r");

Insert strings with apostrophes into database by php

I want to post data into database in safe mode.
For example if i want to add this title to database:
$title = " here is title 'here is title' here is title ";
notice it has apostrophes.
I use this function to make string safe:
function stringsafe($string)
{
$string = strip_tags(trim(addslashes($string)));
return $string;
}
as you see it's adding slashes before apostrophes to make it safe.
I tried to remove slashes when i show the data by stripslashes, it's working but it's has some problems. Is there anyway to post data into database?
On a side note, in fact the general rules of thumb is that, you shouldn't alter user input at all. You should store whatever user input as it is, into your database, so that you can retain user input as original as possible, and only escape it when you need to display or use it.
In your case, yes you are right you have to prevent it from being injected, but you are altering the original input by adding slashes into the original input, which is not very favoured. What if my title contains a string like this <My 21st Birthday Party!> and you stripped it away?
Try using Prepared Statements instead so you can insert any data into your database, without the worries of injection. And only when you need the data to be displayed on a HTML page or console, you escape them accordingly such as htmlentities.

MySQL API - Store HTML tags

I have a form where I can also write HTML tags. I must save this textarea preserving every single HTML tag. So here's the code:
foreach($_POST["comment"] AS $key => $value)
{
mysql_query("UPDATE comments SET title= '".$value["title"]."', comment = '".$value['comment']."' WHERE id = '".$value["id"]."'");
}
When I try to save this:
<b>Hello</b>
In MySQL I get this result:
<b>Hello</b>
I must keep every single HTML as it is. If I write <b> I must save exactly <b> in database. I tryed escaping, html etities, quotes, strip slashes (...) but this guy keep saving everything in the wrong way.
p.s. Before you ask yes, description field is TEXT tupe with UTF-8 encoding.
Have you tried using http://php.net/manual/en/function.htmlspecialchars-decode.php on the mentioned value? This should do exactly what you're asking.
try running:
$sStr = '<b>Hello</b>';
echo htmlspecialchars_decode($sStr);
And it will be encoded properly. Feeding that to the database stores the value correct.
Also, but this is more of a side-notice, you really shouldn't save post data without validating the input. I do assume this is just a quick example and not production code? However, just a suggestion.
You need to escape the entry. If you are using the mysql method, you need the mysql_escape_string function like:
$string = mysql_escape_string("<br>Hello</br>");

What is the securest way to add html/css/js to mysql?

I'm currently using the following PHP class to store html, css and javascript code to my mysql database.
function filter($data) {
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data= strip_tags($data);
$data = mysql_real_escape_string($data);
return $data;}
I' really wondering if the used code is secure enough to store HTML / CSS / JS code in a mysql database?
Yes, MySQL can store any type of text technically safely. Which means, MySQL will save the text as is and will return it again without loosing any data.
Mysql does not differ between the content of the text, so it makes no difference if it is HTML, CSS, JS code or your friends last email.
However if you output the text later on you should take care that there is no unwanted code injection after you've pulled the data from mysql. But that's not related to MySQL actually.
To make you sql more secure, pass the database handle to mysql_real_escape_string or even better use MySQLi and/or PDO and prepared statements.
Your code
Your code looks like you're trying a lot to prevent something, but in the end it turns out pretty useless:
function filter($data) {
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data= strip_tags($data);
$data = mysql_real_escape_string($data);
return $data;}
Normalize the data before you process it
First of all you should change the position of the check for get_magic_quotes_gpc to normalize the data the function is working on. It would be even better if your application would not rely on it but just denies working if that option is enabled - see this important information here about that if you care about security.
But for the safeness of your code posted, let's first normalize the input value to the function before processing it further. This is done by moving the check to the top of the function.
function filter($data)
{
// normalize $data because of get_magic_quotes_gpc
$dataNeedsStripSlashes = get_magic_quotes_gpc();
if ($dataNeedsStripSlashes)
{
$data = stripslashes($data);
}
// normalize $data because of whitespace on beginning and end
$data = trim($data);
// strip tags
$data = strip_tags($data);
// replace characters with their HTML entitites
$data = htmlentities($data);
// mysql escape string
$data = mysql_real_escape_string($data);
return $data;
}
In this modified function, the magic quotes stuff (which you should not use) has been moved to the top of it. This ensures that regardless of that option is on or off, data will always be processed the same. Your function did not do so, it would have created different results for the same data passed. So this has been fixed.
More Problems with your function
Even the function looks better now, it still has many problems. For example, it's unclear what the function actually does. It does many things at once and some of them are contradictory:
It removes HTML tags which is a sign that $data should not contain HTML
But then you convert the text of $data to have actually contain HTML entities.
So what should the data be? HTML or not? It does not introduce more security if things become unclear because this will benefit that errors come into your program and in the end even pass your security precautions.
So you should just throw away the code and consider the following:
If input to your application is invalid, don't filter it. Instead prevent further use of invalid input. So you need a function to validate input before you make use of it.
Don't change data just because you think this might make something more secure. Instead change and encode data where it is needed and appropriate.
Make your application only work with magic quotes off. Relying on this feature is highly discouraged. And then there is no need to check for that all over in your code.
To store something safely within the database, escape the data prior using it in the query only. Not at some other place of your application. Use Prepared statements for that.
No need to wrangle the data before you put it into the database if it's valid. But you need to properly encode it when output it to the webpage. And only there an application does know in which encoding this needs to be. You do not know that when you put the data into the database.
So if you want to make your code more secure, this is not about throwing a bunch of functions onto some data because you think those are security related. By doing so you don't make your software more secure but less secure.
Never trust user data.
Ensure data is in the format you need it prior processing.
Use the right tool for the job at the right place.
Never use tools at guess. Get knowledge instead, that pays not only security wise.

TextArea Data Sanitizing Before Storing In MySQL

Here's the problem scenario. I have a textbox in which users can input comments. However, if they include HTML tags or <A HREF='javascript:window.alert("Example of a link that displays an alert box");'> link </A>, and when the comments are outputted onto the page from the MySQL database, they actually execute. I'm looking for a way to prevent that from happen and only allow a few HTML tags to be used (like bold, italics, underline).
I'm using this function on my comments before sending the comments from the textarea to be stored on the mysql database:
function sanitize($data)
{
// remove whitespaces (not a must though)
$data = trim($data);
// apply stripslashes if magic_quotes_gpc is enabled
if(get_magic_quotes_gpc())
{
$data = stripslashes($data);
}
// a mySQL connection is required before using this function
$data = mysql_real_escape_string($data);
return $data;
}
Well, there was no answer how to allow certain tags to remain intact.
strip_tags() function, which comes first to one's mind, is not safe at all, it will allow dangerous JS attributes.
So, you have to use some utility like HTML Purifier, or some regexp that will allow only certain tags and eliminate all others or for for BBCode.

Categories