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]);
Related
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']);
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
I have this textarea called personalInfos where i fill the infos in following format :
<p><span class="white">1966 - '69</span><br/> text .... </p>
When i submit it to database, it gets saved ok, same format. When i retrieve the code from database to admin textarea it gets filled ok.
My only problem is on front end where i get displayed the code as text not rendered as html code. So basiclly i see it on the page like this :
<p><span class="white">1966 - '69</span><br/>
Most likely you display fetched code parsed processed by htmlentities() or similar function. This is in most cases the way to go to avoid planting i.e. html in comments. So simply stop doing this after fetching (or insert - depends where you do so) and your content will be outputed as literaly HTML and properly processed by web browser.
You should have a look at htmlspecialchars_decode()
Example
$str = '<p><span class="white">1966 - \'69</span><br/> text .... </p>';
echo htmlspecialchars_decode($str);
Also make sure to escape the single quotes as well.
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 ;)
I'm getting data from my textarea with the following code
$about_me=mysql_real_escape_string(nl2br($_POST['about_me']));
which
1. Receives data, using $_POST.
2. nl2br makes brakes so If I echo this code to user he will see if there were new lines.
3. mysql_real_escape_string to secure code from mysql injections before entering it to database.
So if I echo this code everything works fine.
But If I edit it again through textarea, php goes to mysql gets data, puts it to textarea and I see <br> signs...
How can I get rid of them while editing my text again in textarea ?
How can I get rid of them while editing my text again in textarea ?
Stop using nl2br(), of course. It's entirely wrong here.
You use nl2br() when you want to output data that contains linebreaks to HTML, not when you want to store it in the database. Store data unchanged, format it for viewing.
If you output it into a <textarea> you don't need to use it either, since textareas display linebreaks (whereas HTML in general does not). For the textarea you need htmlspecialchars(), but apparently this is already happening - otherwise you would not see literal <br> showing up.
<?php
function br2nl($string){
$return=eregi_replace('<br[[:space:]]*/?'.
'[[:space:]]*>',chr(13).chr(10),$string);
return $return;
}
?>
Use this while getting data from database and before printing into textarea .
http://php.net/manual/en/function.nl2br.php
Check examples on this page