The code below takes a string protects its using mysqli_real_escape_string.
but not geting expected output working fine without the mysqli_real_escape_string but need that for protection.
$str = mysqli_real_escape_string($con,$_POST['str']);
/*
get each word in the sentence using for-loop then
*/
switch($eachword){
case ':)': $eachword = '<img src="smile.gif">';
break;
/*
and so forth and so on
*/
}
$newstr .= $eachword;
//for-loop ends
**mysqli_query($con,"insert into tbl(comment)VALUES($newstr)");**
e.g
input : $str = "here i am :) fine";
expected output : $newstr="here i am <img src="smile.gif"> fine";
curernt output : $newstr="here i am :) fine";
UPDATE
NOW everything works fine. Thanks to supporters.
You are running mysqli_real_escape_string over some data immediately before … not using at all in your code sample. So it doesn't make any sense.
Use mysqli_real_escape_string immediately before inserting the variable into a string of SQL and nowhere else. (Better yet, use prepared queries and bound arguments).
If you are trying to defend against XSS, then use htmlspecialchars immediately before inserting a variable into a string of HTML.
Don't use either before comparing user input to some text.
UPDATED
Note that you must be already connected to a database, for mysqli_real_escape_string to work, because it takes into consideration, the default character set of your selected database. Are you connecting to a database before using it?
And in your question, I don't even see a query. There will be no advantage in using mysqli_real_escape_string unless you're going to insert the passed string into a database.
Now I see that you're replacing smileys with tag, then you're inserting it into a database. However, if I were you, I would do the following :
function ParseSmiley($str)
{
$smileys = array(
':)' => "<img src='smile.gif' />" //Put all your smileys in this array
);
$parsed_string = strtr($str, $smileys);
return $parsed_string;
}
When you're inserting your content into database, do not convert it into tags. Instead, when you display it, use the function ParseSmiley()
$parsed_string = mysqli_real_escape_string($con,$_POST['str']);
mysqli_query($con,"INSERT INTO tbl (comment) VALUES ($parsed_string)");
Then when you want to display the content, let's say the string is in $content, display it like this :
echo ParseSmiley($content);
Related
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.
I wasn't exactly sure how to word this, but essentially what I need is so when I send a SELECT query in MySQL, it doesn't pay attention to the escape character ( \ ) in the search. For example, if the name I am searching for is foo'bar and I send foo\'bar to the server, is there a way to make the server find foo'bar? This is the MySQL query currently:
function escape_data($data) {
$data = mysql_escape_string (trim($data));
$data = strip_tags($data);
return $data;
}
$champ1 = escape_data($_GET['champ1']);
foreach($db->query("SELECT * FROM champs WHERE name = '$champ1'") as $row) {
$role_verify_1 = $row[$role];
}
the only way I can get foo'bar to return is if I change it to foo\'bar in the MySQL database and I would like not to if it is possible.
The function you want is stripslashes before mysql_real_escape_string, however your real concern should be where the slashes are actually coming from - it looks like you might have magic quotes turned on. This is deprecated - check the link for instructions on disabling it.
The Syntax at PHP requires that.
For example;
name = '$champ1'
Here you have a variable in ' tags. But that variable includes ' inside like foo'bar, its turn to that.
name = 'foo'bar'
as you see php can't understand what is going on there. So it need to clear that problem like adding before ' an \. And inserted item will have slashes before aphostropes.
As a solution you can delete the backslashes before you echo the variable.
$theVariable = str_replace("\", "", $theVariable);
Or you can use PHP's upper version's functions. like stripslashes() before you insert your data.
Good luck.
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.
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?>">
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.