It's pretty simple, I have a text area post on my website, and if I input:
line 1
line 2
line 3
into it, it outputs:
line 1nline 2nline 3
My insert code is:
$status = strip_tags(stripslashes(htmlentities(mysql_real_escape_string($_POST['status']))));
$uid = strip_tags(stripslashes(htmlentities(mysql_real_escape_string($_POST['uid']))));
//more stuff
$sid = rndTxt(16);
$status = nl2br($status);
if (!get_magic_quotes_gpc()) {
$status = addslashes($status);
}
$insert = mysql_query("INSERT INTO mingle_status (uid,sid,status,`timestamp`) VALUES ('$uid','$sid','$status',now())") or
print mysql_error();
and my output code:
while($st = mysql_fetch_assoc($statussql)) {
$status = stripslashes($st['status']);
$sid = $st['sid'];
$td = $st['timestamp'];
?>
<div id="n">
<div id="statuses" class="<?php echo $sid; ?>">
<p><?php echo $status; ?></p>
<div id="statuscomadd" style="background:#E0E0E0;">
Like Dislike<?php echo time_since($td) . " ago"; ?>
</div>
</div>
Any help would be greatly appreciated!:)
you dont need to use nl2br() on insert, you will have to use it while displaying in html
and will have to remove stripslashes before insert
When inserting just do a mysql_real_escape_string() over the values. You only want to change the data (e.g. by using htmlentities() when you are going to display it).
Please also consider to stop using mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process. See the red box? Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is a good PDO tutorial.
Another thing: do you realy need htmlentities()? Because imo a better solution is to use htmlspecialchars(). Otherwise all html entities will be replaced.
Also I don't think you need to use strip_tags(), because you are already doing htmlspecialchars() to protect you against XSS.
Now for you problem is it because you are using stripslashes() which breaks the \n linebreaks. I think you can just drop those add/stripslashes.
You use strip_tags(stripslashes(htmlentities(mysql_real_escape_string()))); which strips the slashes from \n.
Just use mysql_real_escape_string(), or htmlentities( ,ENT_QUOTES) for HTML.
Also, if it's possible use an UTF-8 encoding and htmlspecialchars() instead of htmlentities(). htmlentities() converts every character which has an HTML-representation, while htmlspecialchars() converts only the necessary characters. There's no need to convert everything. See: htmlentities vs htmlspecialchars
Related
Sorry to ask this question, Im sure this question has been asked, but because I dont know the name of this symbol ' I cant really search.
The problem, I have a mysql database with text in it those text might have something like this (Hi I've no idea how to fix this). Once I query that text using php and echo on html, it display this.
Hi I�ve no idea how to fix this
Code:
$sql = mysqli_query($connection,"SELECT Something FROM something WHERE ID = '1';");
$row = mysqli_fetch_object($sql);
$description = $row->DESCRIPTION;
<p style="margin-top: 3%">
<?php echo$description?>
</p>
Always try to set MySQL encoding to UTF-8 as a first step. It will solve most of the issue.
At PHP end you can do like this:-
mysqli_set_charset($connection, "utf8")
If above not used then
Either You have to use htmlentities()
<?php echo htmlentities($description);?>
Or you have to use htmlspecialchars()
<?php echo htmlspecialchars($description, ENT_QUOTES);?>
Take a look at
mysqli_real_escape_string
It should help you with your issue and also improve security of your script (SQL injections).
htmlentities() should also help.
Edit: As mentioned in the comments: Instead of mysqli_real_escape_string, it is actually even more secure to use prepared statements.
Here is a simplified of my code:
$html = "<a class='myclass' href='/path?arg='" . $_GET['param']. "'>mylink</a>";
Today I was reading about XSS attack and I think my code is under XSS attack. Howver I'm not sure, but it smells that.
Anyway, if my thought is right, how can I avoid that? Based on some researches, one way is using strip_tags(). Now I want to know, can I rely on it? And is that fine enough?
This is about encode something with the correct function.
Always look what you want to product, then choose the encoder!
Samples:
When you are building HTML its good to use htmlspecialchars and/or htmlentities.
When you are build SQL its good to use for mysql PDO::quote or mysqli_real_escape_string.
Answer:
In your case, you are building an URL. For this you need to use urlencode.
In addition you also need to escape it to correct HTML with htmlentities, because you are building HTML in the next step.
See the sample in PHP manual -> urlencode link (Example #2).
You should use htmlspecialchars() whenever you want to output a parameter that came from user.
$variable = htmlspecialchars($_GET['param'], ENT_QUOTES, 'UTF-8');
This is my code:
<?php
$lname = "templates/generator";
$link = "<img src=\"{$lname}/data/num_{$row}.png\" alt=\"{$row}\"/>";
echo $link;
?>
It does return this. Instead of an image, in the Firebug I can read the following:
<img src=" templates generator data num_1.png" alt="1">
So basically
it is replacing the slashes with white spaces. Where is the problem in this code?
A better idea would be to stop using messing with your quotes. Just sprintf() for outputting the HTML:
$link = sprintf('<img src="%s/data/num_%s.png" alt="%s"/>', $lname, $row, $row);
Also, while looking at your source, use your browser's View-Source feature, and not Firebug. It may be having it's own issues, as Ben said in the comments.
And to make sure you're not misreading the information, you can use a neat little header() trick:
header('Content-Type: text/plain');
PHP uses Content-Type text/html by default. Add this to the top of your script, and it'll display the HTML without any formatting and you can see what's really going on.
Try this:
Simply you should improve your line like this
$link = '<img src="{$lname}/data/num_{$row}.png" alt="{$row}" />';
Never use same commas in the same line, use different instead.
-
Thanks
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.
I was wondering, whats the best practice on the example below.
<?php
if(isset($_POST['query'])){
$out = $_POST['query'];
}
?>
<div><?php echo $out; ?></div>
<input type="text" value="<?php echo $out; ?>" />
Using the above code would this pose a threat to website. Or would I need to prepare the output before using it as above. By prepare I mean encode it or escape special characters.
I am aware you need to escape it and validate inputs for db use, how about for outputting it?
Yes, since you’re putting it out into HTML you should use encode HTML’s special characters appropriately with htmlspecialchars:
if (isset($_POST['query'])) {
$out = htmlspecialchars($_POST['query']);
}
Besides that, $out is only defined when $_POST['query'] exists; you should think about having a default value if $_POST['query'] does not exist. Because otherwise, when register globals are enabled (that alone is a bad idea) you could set that variable via the URL query string with ?out=….
Yes, you should be using the php function htmlspecialchars
http://php.net/manual/en/function.htmlspecialchars.php
also, see this (accepted answer)
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
dont know about best practise and that depend on the coder i like turnary
echo (isset($_POST['query']))? htmlspecialchars($_POST['query']):"";