Insert strings with apostrophes into database by php - 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.

Related

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>");

Is there any mysql function which is not allow such data which contain script-tag or html-tag?

In my register form, if user disable javacript validation for registeration form and try to insert value <script>alert("hacked")</script> then this value is inserting to in my database table.
Can you please assist me how can I secure my application from that type problem?
Thanks.
When you display data that has been provided by the user, you should use htmlentities() to ensure that any HTML tags get display literally, rather than being rendered by the browser.
Well mysql have REPLACE() function for this.
But in your case you can use strip_tags which will escape all the html tags.
$name = strip_tags($_REQUEST['name']);
If you dont want any special character to be inserted
echo strip_tags(str_replace(array('"','/','(','*',':','=','^','#',';'),'',$name);
This will treat all the remaining as string.
For reference see Manual

Slashes in text output

From a form, I'm asking the user to enter some text. I will retrieve this text using $_POST['text'].
The user enters the string "It's my text!"
$newText = mysql_real_escape_string($_POST['text']);
Now on the very same page after I've inserted $newText into the database I want to display
the text to the user and also use it as the value of an input text box using PHP.
// I want to make sure the user hasn't added any unsafe html in their string
$newText = htmlentities($newText);
echo "You've entered: " . $newText . "<br />";
echo "<form action=someaction.php method=post>";
echo "<input type=text value=\"" . $newText . "\">";
echo "</form>";
The output is:
You've entered: It\'s my text!
[It\'s my text!]
How do I avoid these slashes, and should I be doing anything else with my data?
You're passing the text through mysql_real_escape_string() which, as the name suggests, escapes the string, including apostrophes. mysql_real_escape_string() is meant only for preparing the data for saving to database. You shouldn't use it when displaying data to the user.
So, the solution is simple: remove the line and use htmlentities() only. Use mysql_real_escape_string() when you're saving the string to database (and only then).
Only use mysql_real_escape_string() on the variable you want to use in the query, because it will add slashes to escape some of the characters in the string. This works great for mysql, but when want to use it on the page it will look weird.
You could make 2 variables, 1 for MySQL and 1 for displaying the raw text.
$text = $_POST['text'];
$db_text = mysql_real_escape($text);
Also note that you should use strip_slashes() on the data you get from the database later, to remove the slashes.
Hope this clear things up a little bit.
Now on the very same page after I've inserted $newText into the database I want to display the text to the user
That's what you are doing wrong.
An HTTP standard require a GET method redirect after every successful POST request.
So, you have to redirect the user on the same page, where you may read inserted data from the database and show it to the user.
As for the mistake you made - just move escaping somewhere closer to the database operations, to make sure it is used only for the purpose (YET it is used obligatory, without the risk of forgetting it!).
Ideally you have to use some variables to represent the data in the query, and some handler to process them.
So, the query call may look like
DB::run("UPDATE table SET text=s:text",$_POST['text']);
where s:text is such a variable (called placeholder), which will be substituted with the $_POST['text'] value, properly prepared according to the type set in the placeholder name (s means "string", tells your function to escape and quote the data)
So, all the necessary preparations will be done inside and will spoil no source variable.
save normally using mysql_real_escape_string()
and when you want to display it in a form:
htmlspecialchars(stripslashes($row['text_data']))
it will do the trick.

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...

Disallow characters in text field

Should I disallow characters like ",',>,<,\ ... to be typed in an upload forms text field? The text will be send through PHP to a blog.
I heared that some characters might cause trouble and could be used to "hack / harm" servers. Which characters should be restricted?
Thanks for your input.
Michael
There is no need to restrict anything. The problem is that you have to sanitize all user input; for this specific type of data (possible HTML) it is necessary and enough to use htmlspecialchars on all user-provided data before displaying it as part of your page.
For example, if your form has a textarea named post-body, you should receive the user input (e.g. with $_REQUEST['post-body']) and save it to your database as-is (warning: use mysql_real_escape_string or PDO to protect yourself from SQL injection at this stage!). When the time comes to display it, you would retrieve it from the database and print it with something like
echo htmlspecialchars($postBody);
See this question for some more background on data sanitization.
Users data should be sanitized by htmlspecialchars function each time when you output users data, to avoid XSS-attacks.
Also, to work with users data in sql-queries, use PDO and prepared statements or mysql_real_escape_string function to avoid SQL-injection. Example.
<? $string = str_replace("\\\"", "\"", $string);
$string = htmlspecialchars($string);
$string = preg_replace( "/\r\n|\n|\r/", "<br>", $string ); ?>
<input type = "text" name = "string" id = "string" value = "<?=$string?>">

Categories