Echo html from a database - php

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 &lt;div&gt;, 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:
&lt;div&gt;stuffInDiv&lt;/div&gt;
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']);

Related

How to retrieve some special characters (& ,<) from sql while using AJAX

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

Storing HTML in MySQL

I'm storing HTML and text data in my database table in its raw form - however I am having a slight problem in getting it to output correctly. Here is some sample data stored in the table AS IS:
<p>Professional Freelance PHP & MySQL developer based in Manchester.
<br />Providing an unbeatable service at a competitive price.</p>
To output this data I do:
echo $row['details'];
And this outputs the data correctly, however when I do a W3C validator check it says:
character "&" is the first character of a delimiter but occurred as data
So I tried using htmlemtities and htmlspecialchars but this just causes the HMTL tags to output on the page.
What is the correct way of doing this?
Use & instead of &.
What you want to do is use the php function htmlentities()...
It will convert your input into html entities, and then when it is outputted it will be interpreted as HTML and outputted as the result of that HTML...For example:
$mything = "<b>BOLD & BOLD</b>";
//normally would throw an error if not converted...
//lets convert!!
$mynewthing = htmlentities($mything);
Now, just insert $mynewthing to your database!!
htmlentities is basically as superset of htmlspecialchars, and htmlspecialchars replaces also < and >.
Actually, what you are trying to do is to fix invalid HTML code, and I think this needs an ad-hoc solution:
$row['details'] = preg_replace("/&(?![#0-9a-z]+;)/i", "&", $row['details']);
This is not a perfect solution, since it will fail for strings like: someone&son; (with a trailing ;), but at least it won't break existing HTML entities.
However, if you have decision power over how the data is stored, please enforce that the HTML code stored in the database is correct.
In my Projects I use XSLT Parser, so i had to change to   (e.g.). But this is the safety way i found...
here is my code
$html = trim(addslashes(htmlspecialchars(
html_entity_decode($_POST['html'], ENT_QUOTES, 'UTF-8'),
ENT_QUOTES, 'UTF-8'
)));
And when you read from DB, don't forget to use stripslashes();
$html = stripslashes($mysq_row['html']);

Step by step storing textarea mysql php

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

Transform html tags from db

I am using a jquery editor.And the content will be saved in the database along with the html tags . That is for example I have typed "aneesh" in the editor and using editor makes the text bold and italics the saved the content to db .
So the content will be saved in the db along with text and html tags
Now i want take the content from db and want show the text in formated ways that is need to transform the html tags that in my the content want to show like this aneesh Is there any way for this please help me
To store and retrieve html you should use htmlspecialchars() - this preserves html tags etc etc when saving and htmlspecialchars_decode() - this converts them back to proper html that can be displayed - when displaying the retrieved content.
Storing using this and calling the decode function when populating the textarea behind the wysiwig editor will/should have kept everything preserved.
Or you can also use htmlspecialchars()
$a=htmlspecialchars($a);
<text>$a</text>
wud help u save and retrieve the html characters
Just select the data out of database (i'm using PDO): and echo/post the result to the document without string formating:
$sql = 'SELECT * FROM table;';
$stmt = $DB->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['result'];
if you have content with html tags like i-e <b>Hello</b> in the database, and when you return it from the database again, the jquery editor that you are using will automatically remove those tags and will transform your text again and make it i-e bold (if hello in case).
There is no need to do anything but just echo it out.
you need to use javascript for better and easy solution.
get raw html content from db (with php) to show web browser (with javascript): innerHTML or .html() (JQuery)

Parse text from database table as HTML in final rendered PHP page

One of the fields in our PHP page is a description - occasionally there are website links included. However, when pulling this data from the database table the links remain non-clickable. How can I parse text from database table as HTML in final rendered PHP page? Thanks!
Do you mean something like this?
<?php
echo "<a href='$linkLocation'>$linkName</a>";
?>
[Edit]
Server-side you could transform the orginal text ($det[9]) like this (based on this SO question):
<div id="text"><?php
echo preg_replace_callback(
'/http:\/\/([,\%\w.\-_\/\?\=\+\&\~\#\$]+)/',
create_function(
'$matches',
'return \'\'. $matches[1] .\'\';'
),
$det[9]
);
?></div>
[Edit: merged the original code from your comment]
[Edit: fixed typo]
Are your text stored as HTML or is it just a text containing URLs?
Follow these steps
Change the db feild to text,
While inserting data convert the html entities and escape the quotes.
while retrieving do the reverse process and you can retrieve data in html format this way

Categories