so i'm getting confused by all the topics about storing and displaying textareas with correct linebreaks and not allowing any HTML markup whatsoever.
Right now i am escaping the input, then storing it as a text and then trying to display it with echo nl2br($text); It still won't work though.
So how is it supposed to be handled so that the input is safe, it won't allow any HTML on display, how to display it correctly and so on?
This is what happens when i run my current code..
Step 1:
Textarea input:
ROW 1
ROW 3
ROW 4
ROW 6
Escaped variable : $text = $mysqli->real_escape_string($_POST['textarea']);
Step 2:
SQL-query to insert into db. Stored in database as:
ROW 1\r\n\r\nROW 3\r\nROW 4\r\n\r\nROW 6
Step 3:
Fetch it with SQL, display with an echo nl2br($text); which results as ROW 1\r\n\r\nROW 3\r\nROW 4\r\n\r\nROW 6
I guess that the way it is stored prohibits the usage of nl2br since there ain't really any newlines stored but only \r etc, i'm kinda lost at this one and it's getting late so...
Any guidance would be appreciated.
In your case - since you want to strip any markup from the input....
$text = strip_tags($_POST['textarea']);
$text = $mysqli->real_escape_string($text);
mysqli->query("INSERT INTO yourtable (content) VALUES ('$text')");
...but when you want to output it again to a browser - you STILL NEED TO escape it appropriately....
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_assoc()) {
print "<div>" . nl2br(htmlentities($row['content'])) . "</div>";
}
}
The only time you apply any sanitization to data within PHP is at the point where it leaves PHP (going to a database, going to a browser, going to a log file....) and the method you use for transforming the data is dependant on where the data is going
Related
I am saving user fed text entered in a text box into the database and then retrieving the entered text using ajax(using JavaScript and not jQuery).
All special characters are getting inserted well in mysql but it is not able to retrieve the data containing special characters. Greater than (>) symbol is getting retrieved successfully but & and < is causing the whole page to load without any result.
Code for inserting data:
for($i=0;$i<$No_of_Inp_Fields; $i++)
{
$Desc = $_POST['txtdesc'.($i).''];
$inquery="INSERT INTO DETAILS VALUES ('$Desc')";
$sSql = mysql_query($inquery);
}
Code for retrieving the data
$queryPopIP=mysql_query("select Desc from DETAILS where Nm='$tag'");
$resPopIP=mysql_fetch_array($queryPopIP);
$DesPop=$resPop[0];
This is sent as a response using php
Code for displaying the data(using javascript)
var desIP=serverResponse.split('_');
document.getElementById('popdiv2').innerHTML="<b>"+desIP[1];
No jQuery... add the text as a text node. It'll preserve the angle brackets or other special characters.
document.getElementById('someElement').appendChild( document.createTextNode('<b>sushi</b>') );
I think this what you are asking? Honestly still not a 100% clear.
If that's not it, you probably need to call htmlentities on your data (if you are using PHP) when you are displaying the values of your data.
EDIT
Since it looks like $DesPop is what you send through AJAX, do this in your PHP
$DesPop = htmlentities($resPop[0]);
I am attempting to write html data from a mysql database to a document using php. My code is below:
$content = html_entity_decode($dataToLoad['Text']);
echo $content;
$dataToLoad['Text'] contains this text data from the database:
<div>stuffInDiv</div>
What I would like to happen is for this text to be written as an actual div element in the document, but instead it is being written as a string. How can I force php to write it as an element?
Update for clarity:
To clarify, my issue isn't with decoding the html entities in the database, it's with writing the decoded html to the document. When I do:
echo $content;
where $content contains
<div>stuffInDiv</div>
I get the string "<div>stuffInDiv</div>" when really what I want to have is a div containing the string "stuffInDiv"
The Answer
It's possible your data has been encoded twice. Try echo $content; and then go to View Source in your browser. If it starts with <div>, then you'd need to run html_entity_decode twice. There is rarely a good reason, however, to store the HTML in the database with the entities encoded. It'd make more sense to store it raw and encode it when need be (e.g. if the code were placed into a textarea).
$content = html_entity_decode(html_entity_decode($dataToLoad['Text']));
echo $content;
The Reasoning
The reason is because the raw data in your database looks like this:
<div>stuffInDiv</div>
Your browser would print this on the screen:
<div>stuffInDiv</div>
The first time you run html_entity_decode, it does exactly that, i.e. it replaces & with the & character (& is the code for the ampersand).
This produces:
<div>stuffInDiv</div>
The web page spits out the encoded entities, i.e.:
<div>stuffInDiv</div>
Running html_entity_decode a second time would replace < with < (less than sign), > with > (greater than sign), etc.
This produces:
<div>stuffInDiv</div>
Which would be outputted to your page as:
stuffInDiv
Your Database Setup
As a note to your database:
When storing information in the database, do not encode the HTML at all. Unless HTML is being outputted onto a web page, it is no different from any other string and you shouldn't treat it differently. So if you were adding data to a table in your database that contains code, just do something like this:
INSERT INTO `my_content` (`name`, `content`) VALUES ("My Page", "<div>stuffInDiv</div>");
If you were obtaining this data from a textarea, use:
$connection->query('INSERT INTO `my_content` (`name`, `content`) VALUES ("'.$connection->real_escape_string($_POST['name']).'", "'.$connection->real_escape_string($_POST['content']).'");');
Without doing anything to manipulate the value of $_POST['content']. If you need to place that data back into the textarea (say, editing a page):
$result = $connection->query('SELECT `content` FROM `my_content` WHERE `name` = "'.$connection->real_escape_string($_GET['edit_page']).'");');
if ($row = $result->fetch_assoc()) {
print '<textarea name="content">'.htmlentities($row['content']).'</textarea>';
}
You can replace html entities with str_replace... (but surely there's an easier way)
$ar = get_html_translation_table();
$dataToLoad['Text'] = '<div>stuffInDiv</div>';
echo str_replace($ar, array_keys($ar), $dataToLoad['Text']);
I was having an issue when I input comments into a log table the display would be incorrect.
For example when I input:
1
2
3
It would show up as:
1
2
3
To deal with this problem I commented out some of the code and added this regex line:
//$notes= str_replace("</br>","<br>",$sqlresult['Notes']);
//$notes = str_replace("\r","",$sqlresult['Notes']);
//$notes = str_replace("\n","",$sqlresult['Notes']);
//$notes = str_replace("\\","",$sqlresult['Notes']);
//$notes = str_replace("\r","<P>",$sqlresult['Notes']);
$notes = trim(preg_replace('/\s\s/', '<br>', $sqlresult['Notes']));
However now I am receiving an error when text is pasted from an application that appears as one line is coming up with a lot of extra lines in betweem.
E.g.
Files are.. CDSEYE SUBMIT BY M99-CDSENTD
Display:
Files are...
CDSXEYE
(10 EXTRA BLANK LINES)
SUBMIT BY M99-CDSENTD
Is there anyway I can get the $notes to display input EXACTLY how it is inputted?
The reason you had to use the
$notes = trim(preg_replace('/\s\s/', '<br>', $sqlresult['Notes']));
line in the first place is because there was something wrong with the way you were handling input and storing it in a sql database. We merely plugged that hole by removing that extra newline at the end. If we wanted a true 1 to 1 input to output, we would need to look at the way the data is stored from the input textbox to the sql database. Also how it is being pulled from that database and displayed back to the output. If somebody else wrote this code, then it may take a while to find how that was done.
final answer ended up being:
$notes = trim(preg_replace('/\r\r/', '<br>', $sqlresult['Notes']));
I think the problem lies in the second to last line, where you're replacing \r with <p>, which adds an extra blank line. Try <br> instead.
Your replacing every 2 spaces with a line break (<br>), this would be the reason for your breaks.
$notes = trim(preg_replace('/\s\s/', '<br>', $sqlresult['Notes']));
I suggest remove the above code and then put
echo nl2br($your_text_variable); //in the view
I am parseing a page and saving the retrived data in mysql db. Everything is ok except the price of the product. After extracting price,when i use print_r($price) i get the actual value but while saving the same $price in my database, i get only a part of it.
for example:-
while using print_r($something); //output is 2 458
while saving in database $something, the saved value is only 458.
I think that the problem is due to space between 2 and 4. I can understand that this is a very simple question for most of you, but right now i am not able to solve it.
Thanks a lot ahead for support!
MySQL is pretty permissive about what data you can insert into its fields. In this case you are trying to insert a string that contains two numbers into a numeric field, it's doing its best to extract a single number from that data but is getting it wrong.
All you need to do is remove the space(s) before you insert:
$something = str_replace(' ', '', $something);
or using a regular expression you could remove any non-numeric character:
$something = preg_replace("'[^0-9]'", '', $something);
I've recently thrown together a basic PHP webpage that lists information pulled from an MySQL table and displays it in various sorts. I'm wanting to allow the user to add a new item to the table, edit an item in the list and delete an item in the list without refreshing the page (Ajax).
This currently goes;
To add/edit an article you click on a link which prompts the popover ajax form, and fills it's contents (if editing) by performing the function setEdit(comment) as below;
<a class="popup-button" title="<?php echo $row['comment']; ?>" onclick="setEdit('<?php if($row['comment']){ echo $row['comment']; } else { echo "Enter comment here..."; } ?>');"><?php echo $row['listitem']; ?></a>
The setEdit() comment is as follows;
function setEdit(editcomment)
{
if(editcomment){ document.getElementById('help-us-comment').value=editcomment; }
}
Which is then, after submitting the ajax form, handled by the following php code;
if(isset($_POST['comment_text']))
$comment=$_POST['comment_text'];
$sql = "INSERT INTO table SET
comment='$comment'";
Problem: I'm having constant issues trying to get the database contents through 1, 2, 3 without falling over at a new line, single or double quote. I've tried endless combinations of replacing tags, htmlspecialchars and nl2br with no half successes - where it's got to the point that it's so convoluted and encoded/decoded now that I'm assuming that there is a far simpler and obvious way that I'm missing.
The main problem happens when trying to load the data into the form, typically having either the form fall over and refuse to populate at all (typically by the a link becoming broken by the data extracted i.e. single quote or new line) or the form being populated with special characters instead of plain text to edit.
I've tried to go into as much detail as possible, but if any more is needed I'm happy to provide. Also apologies if this is an obvious fix/mistake, and I'm being an idiot.
You have two problems here: storing and displaying.
To display you should look in to htmlentities that makes it safe HTML (it does all the quotes replacing, html encoding, etc. for you) so that your string to be safe to be displayed as plain text, or as inputs' values.
To store the data, you should sanitize your queries. You could use mysqli and bind parameters, or use mysql_real_escape_string to escape your input manually.
Otherwise, say hi to Bobby Tables ;)