How to secure $_POST of php without making quotes and other things - php

I have tinyMCE editor which is passing data to php processing file.
If I use $variable=$_POST(['tinyMCE_textarea']); everything is ok.
But I want to secure it so nothing bad will come from user who entered some data into textarea.
And when I use $variable=mysql_real_escape_string($_POST(['tinyMCE_textarea']));
The result becomes dammaged with some \" signs. So how can I add maximum security without changing the variable ?

TinyMCE is able to clean up data, however it is critical that you don't rely on client-side stuff.
To secure data for database, you use mysql_real_escape_string(). The result is intended for use with mysql and not for display.
To secure data for display, you use the htmlspecialchars() function. htmlentities() also works but would convert all applicable entities, so for security you only need htmlspecialchars().
So the simplified picture is
.// Insert to database
mysql_query("INSERT INTO data (content) VALUES ('" . mysql_real_escape_string( $_POST['tinyMCE_textarea'] ) . "')");
.// Display to user - doesn't matter whether the data is from post or database
echo htmlspecialchars ( $_POST['tinyMCE_textarea'] );

use prepared statement or PDO.
use htmlentities() or covert atleast '<' and '<' '"' to "& gt;" and so ..

Just remember to escape the user input before outputting (using for example htmlentities()) and escape the string before storing it in your database.

Use SQL parameter binding, and you are safe from any injection.

Related

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.

Prevent escape_string slashes from being printed

I've written a blog system which works quite well, except for one little thing. I'm using a mysqli::real_escape_string to prevent the system from being exposed to SQL-injections. However, if someone writes a comment with a " or ' in it, these will be shown as \" or \', which isn't exactly user friendly.
Is there a way to prevent these from being written, or removing them before being echoed with PHP?
In your situation, escaping happen twice (probably because of the enabled settings "magic_quotes_gpc=On")
Example:
Is your name O'reilly?
When this parameter transmission browser (client) -> php (web-server) with magic_quotes_gpc = on
Is your name O\'reilly?
Then your code mysqli_real_escape_string
Is your name O\\\'reilly?
The result is stored in the table:
Is your name O\'reilly?
Сonclusion:
Outdated setting «magic_quotes_gpc» to disable.
NOTE. To prevent SQL-injection when the sql query is more expedient to use «prepared statements» in this case, the parameters do not require escaping.

SQL injection help

So I was just testing out the mysql_real_escape(); function and what that does is puts a \ before the ". The when the content is echoed back out onto the page I just get content with \'s before any ". So let's say I posted """""""""""""""""""""""""""" all I get is \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" echoed back.
Is there some code to remove the \ when it's echoed back onto the page?
By adding those slashes, mysql_real_escape_string just converts the string into the input format for the database. When the data comes out of the database, it should come out without any of the slashes. You shouldn't need to remove them yourself.
Using stripslashes like others are suggesting would do the opposite of mysql_real_escape_string in most cases, but not all of them, and you shouldn't rely on it for that purpose. Mind you, if you find yourself needing to use it for this, you've already done something else wrong.
stripslashes()
http://php.net/manual/en/function.stripslashes.php
You don't need to unescape, ie. remove the slashes - they don't get inserted into the DB. They are only for passing data to MySQL, they are not written to the db. When you SELECT the data, you won't see the slashes.
Do you know how mysql_real_escape() works. Hint: It allows to encode string for SQL usage. For example mysql_query('SELECT * FROM users WHERE name="'.mysql_real_escape_string($name).'"');. It can be used to insert string which won't escape the quotes for example like " or 1=1 -- " making SELECT * FROM users WHERE name="" or 1=1. You have to activate it just before inserting it database.
When you will read this data, slashes won't exist in any way.
Actually, looking at what is below, I will make this answer, not comment...

Specifying some part of the page to be interpreted as plain text

I am beginner in web development, I am developing a site that allows user to post various discussions and others comment and reply on it. The problem I am facing is, the user can post almost anything, including code snippets and any other thing which might possible include single quotes, double quotes and even some html content.
When such posts are being posted, it is intervening with the MySQL insert query as the quotes are ending the string and as a result the query is failing. And even when I display the string using php, the string is being interpreted as html by the browser, where as I want it to be interpreted as text. Do I have to parse the input string manually and escape all the special characters? or is there another way?
You need to read up on a few things
SQL Injection - What is SQL Injection and how to prevent it
PHP PDO - Using PHP PDO reduces the risk of injections
htmlentities
The basic premise is this, sanitize all input that is coming in and encode everything that is going out. Don't trust any user input.
If possible, whitelist instead of blacklisting.
EDIT :
I you want to display HTML or other code content in there, users need to mark those areas with the <pre> tag. Or you could use something like a markdown variation for formatting.
Use PDO, prepared statements and bound parameters to insert / update data, eg
$db = new PDO('mysql:host=hostname;dbname=dbname', 'user', 'pass');
$stmt = $db->prepare('INSERT INTO table (col1, col2) VALUES (?, ?)');
$stmt->execute(array('val1', 'val2'));
Edit: Please note, this is a very simplified example
When displaying data, filter it through htmlspecialchars(), eg
<?php echo htmlspecialchars($row['something'], ENT_COMPAT, 'UTF-8') ?>
Update
As noted on your comment to another answer, if you want to maintain indentation and white-space when displaying information in HTML, wrap the content in <pre> tags, eg
<pre><?php echo htmlspecialchars($data, ENT_COMPAT, 'UTF-8') ?></pre>
Look at mysql_real_escape_string and htmlentities functions in PHP manual.
You can also read the Security chapter in PHP manual.
To avoid the breaking of queries in database (which means you're not escaping them, leaving big holes for sql injection) you use mysql_real_escape_string($string) on the value before passing it to the query string, enclosing it in quotes also.
Ex. $value = mysql_real_escape_string($value); // be sure to have an open connection before using this function.
$query = "select * from `table` where value = '".$value."'";
As for displaying in html, you should at least echo htmlentities($string) before outputting it to the browser.
Like echo htmlentities($mystring, ENT_QUOTES)`;
Edit:
To preserve withe spaces, you can use nl2br function (which converts linebrakes to the html equivalen <br />) or go for a little deeper $string = nl2br(str_replace(" ", " ", $string));, but html code would look a bit ugly, at least for me
Reference: htmlentities and mysql_real_escape_string. nl2br
use mysql_real_escape_string. It is a good practice to use this on all user inputs to prevent SQL Injection attacks.

secure form data for mysql

I have been using:
if ($_POST['Comments']!=""){
$comments = mysql_real_escape_string($_POST['Comments']);
}else{
$comments = "";
}
ever since a user added and apostraphy to their data and it broke my sql statement. I thought this also secured the data at the same time. But just now I got a submission and in the comment field in the database I see:
/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r
seohelp
And the email I get when someone submits had the text with the links actually working.
I thought mysql_real_escape_string() was supposed to get rid of all that?
Any suggestions? I was thinking of doing a function that does all the string cleaning for me in a few different steps. But if there is a way to secure in just one step that would be great.
mysql_real_escape_string() only protects* you against SQL Injection, not against Cross-Site Scripting (XSS).
* mysql_real_escape_string() doesn't behave properly when used in conjunction with SET NAMES because it is unaware of the charset being used. Use mysql_set_charset() instead.
In order to protect yourself against XSS, you must also use htmlentities() or htmlspecialchars() either at insert time (before mysql_real_escape_string()) or at display time.
$escaped = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
If you want to allow some HTML content, use HTML Purifier with a whitelist of elements and attributes you want to allow.

Categories