Store data in html element - php

I have dynamic content which I generate with PHP, and i want to store some various text in data attribute. Bu the problem is that i need to escape various characters that could damage my entire html
So I need to do some kind of encoding with php and then decode that string with javascript when i want to use that data, what would be the best way to do that?
And just to clarify i do not want to use any inputs or anything like that, i need to store this data in various elements for example a or div and so on...

If all you want is to pass some data to JavaScript, why not just write it directly to a variable:
<html>
<head>
<script>
var data = <?php echo json_encode($data); ?>
</script>
<!-- etc. -->
Anyway, if you want to do it your way, you can use htmlspecialchars to escape arbitrary data before putting it in an HTML attribute:
<div data="<?php echo htmlspecialchars('"\'!)(#UI#_!)(#JP_!()#J'); ?>">Example</div>
If you then read that with JavaScript, it should understand the HTML encoding, so you won't need to do anything special to read it.
If your data is more complex, but not binary, you could JSON encode it, then use htmlspecialchars:
<?php
$data = array();
$data["a"] = 123;
$data["b"] = "example";
$jsonData = json_encode($data);
$escapedJsonData = htmlspecialchars($jsonData);
echo "<div data=\"$escapedJsonData\">example</div>";
?>
You can then read that data in JavaScript using JSON.parse:
var yourDiv = getDivSomehow();
var data = JSON.parse(yourDiv.getAttribute("data"));
If your data is binary, you can base64 encode it:
<?php
$data = someImage();
$encodedData = base64_encode($data);
echo "<div data=\"$encodedData\">example</div>";
?>
Presumably there's some way to decode this in JavaScript.

Related

PHP how to save HTML string into database

In response to an API call, I'm getting a full HTML script. Full means it includes HTML CSS and Javascript. Now I have that HTML as string in PHP variable.
$content = '<html>
<head>
<script>--Some javascript and libraries included--</script>
<title></title>
</head>
<body>
<style>--Some Styling--</style>
</body>
</html>';
Now, what is the best way to save this variable in Database and How?
As a string with VARCHAR or TEXT type?
As a string with Base64 Encoded with VARCHAR or TEXT type?
As a Binary with BLOB type?
Or any other you would like to suggest(May be Serialize or Pack)?
I use base64 encoded data to store in my Database with the BLOB datatype. The boilerplate code is as follow.
$content = '<html>
<head>
<script>--Some javascript and libraries included--</script>
<title></title>
</head>
<body>
<style>--Some Styling--</style>
</body>
</html>';
To encode data in base64
$encodedContent = base64_encode($content); // This will Encode
And save the data in database with BLOB. Now after retrieve data, just decode it as follow.
$ContentDecoded = base64_decode($content); // decode the base64
Now the value of $contentDecoded is the plain HTML.
If you base64 encode it you increase the storage size by rougly 30% and you need to decode it each time you display it. Look at the table structure for Wordpress, the most widely used software that stores html on a mysql database using php. What do they use? LONGTEXT. In your case TEXT is probably better because you probably have a good idea about the size of the page.
Store HTML into a variable using addslashes() function.
$html = addslashes('<div id="intro">
<div id="about" align="left">
<h2 class="bigHeader" dir="rtl"HEADER</h2>
<img src="img/Med-logo.png" alt="" />
<div id="wellcomePage" class="text-left text" dir="rtl">
<p>...some words....</p>
<p>.some words....</p>
<p> </p>
</div>
</div>
</div>');
After this, form an SQL query.
$sql = "UPDATE `Pages` SET `content`= '".$html."'";
and you have to add stripslashes when retrieve from DB
you can use base64_encode and store that string into db with text/blob type of field
I would recommend you to use TEXT. Blobs are typically used to store images, audio or other multimedia objects. read more about bolobs
Data type to store HTML in Database would be TEXT.
Use mysql_real_escape_string() to store html text in database
$content = '<html>
<head>
<script>--Some javascript and libraries included--</script>
<title></title>
</head>
<body>
<style>--Some Styling--</style>
</body>
</html>';
$html = mysql_real_escape_string($content);
See this: I did nothing...
I use it like this ..working just fine and also saving in mysql and also retrieving back properly.
$editorContent = $_POST['textarea'];
$a = $editorContent;
$insert = $db->query("INSERT INTO psd ( psdata) VALUES ( '$a')" );

Weird passing php string to javascript sometimes not work

how i what it to work:
goal: make a album viewer without reload the page, with a img html element, change img SRC dynamically with javascript, but image url's stored in php variables and what copy to javascript array.
Problem: example have album where have 17 picture, if i echo in php then $i count from 1-17 but in javascript count to 2-12 and 15-17 so ignore 1,13,14 etc. have no ideea why because no difference in data, so DataPicId[13] is undefined but 15th index or 12th index got value normally.
while($row = mysql_fetch_array($SQLpic))
{
$i=$i+1;
$PicId=$row['id'];
$Url=$row['url'];
$Desc=" ".$row['description'];
$UpUser=$row['uploader'];
$Update=$row['udate'];
echo"<script>
nr=Number('".$i."');alert(nr);
DataPicId[nr]=Number('".$PicId."');
DataPicUrl[nr]='".$Url."';
DataPicDesc[nr]='".$Desc."';
DataPicUser[nr]=Number('".$UpUser."');
DataPicDate[nr]='".$Update."';
alert(DataPicUrl[nr]);
</script>";
$ThumbUrl=GetNameOnly($Url);
echo "<div id='PicBoxOut'>
<div id='PicBoxIn' onclick=SelectSrc('".$i."');>
<a href='javascript:void(0);'>
<img src='".$ThumbUrl."' border='0'></a>
</div></div>";
Without seeing the generated html / javascript, I would guess that your variables are breaking your javascript. That could be for example a single quote in the description of a photo.
To make sure that you output valid javascript, it is better to send your complete row-set to javascript as json and build your html in javascript using that json.
So something like:
<?php
// Note that normally you would have done this already in a controller
// and not when you are outputting html
$rows = array();
while($row = mysql_fetch_array($SQLpic))
{
$rows[] = $row;
}
?>
<script>
var json = <?php echo json_encode($rows); ?>,
object = JSON.parse(json);
// now `object` will contain all your rows in a javascript object / array
</script>

best way to store html in sql using php - display in htmlText in as3

I am having many issues getting html to display correctly in my using a dynamic textField in as3. I am having two main issues.
Either the <br> and <p> are not showing he leaves no line breaks or not the correct formatting with no spaces between some words etc...
there is an error loading because I have it stored in the database wrong, or I am sending the var to flash wrong so flash can't read it or display it correctly.
I understand there are a few levels of complexity to this that could be found in one or all of these 3 codes.
Storing it in the database and using best format.
Pulling it from the database and converting it to a string that can be sent to as3.
Getting the as3 to display the html correctly.
I am not worried about css styles or any other html. I just want it to display the format correctly with the right line breaks etc...
One important note. I am pulling the html from an external page so I don't have control over all the extra html code in this, such as styles etc....
In mySql I am storing the html in a TEXT type as opposed to varchar etc...
Here is the php code that is storing the html text.
<?
// I am only showing what I believe to be the relevant code.
//I am mainly concerned about the Content var.
$content = trim(strip_tags(addslashes($content)));
// Also tried the line below without the strip tags
$content = trim(addslashes($content));
mysqli_query($con,"INSERT INTO myDataBase (Content, Title) VALUES ('$content','$t'");
?>
Here the php code that is getting the content from the sql.
<?
while($row = mysqli_fetch_array($result))
{
$Content[] = stripslashes($row['Content']);
}
/// sending to as3
echo "&Content1=$Content[1]";
?>
Here is the as3 code that is displaying the html. (Not working well)
public function popeContent()
{
var formatT = new TextFormat( );
formatT.bold = false;
formatT.color = 0x454544;
formatT.font = "TradeGothic";
formatT.size = 40;
formatT.leading = 10;
formatT.font = "Arial";
theContent.multiline = true;
theContent.wordWrap = true;
theContent.htmlText = Content1;
theContent.width = 1075;
theContent.y = 0;
theContent.x = 0;
theContent.autoSize = TextFieldAutoSize.LEFT;
theContent.setTextFormat(formatT);
addChild(theContent);
}
Any help to send me in the right direction would be appreciated. Thanks so much.

Having trouble passing text from MySQL to a Javascript function using PHP

So here's the problem. I have data in a MySQL DB as text. The data is inserted via mysql_real_escape_string. I have no problem with the data being displayed to the user.
At some point I want to pass this data into a javascript function called foo.
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{$someText}')\">";
If the data in $someText has line breaks in it like:
Line 1
Line 2
Line 3
The javascript breaks because the html output is
<img src=someimage.gif onclick="foo('line1
line2
line3')">
So the question is, how can I pass $someText to my javascript foo function while preserving line breaks and carriage returns but not breaking the code?
===========================================================================================
After using json like this:
echo "<img src=someimage.gif onclick=\"foo($newData)\">";
It is outputting HTML like this:
onclick="foo("line 1<br \/>\r\nline 2");">
Which displays the image followed by \r\nline 2");">
json_encode() is the way to go:
$json = json_encode($someText); # this creates valid JS
$safe = HtmlSpecialChars($json); # this allows it to be used in an HTML attribute
echo "<img src=someimage.gif onclick=\"foo($safe)\">";
You can see a demo here: http://codepad.org/TK45YErZ
If I'm not interpreting badly you may do this:
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{".trim( preg_replace( '/\s+/', ' ',$someText ) )."}')\">";
You'll save yourself a lot of headaches by pulling the JavaScript out of the HTML:
<img id="myImage" src="someimage.gif"/>
<script type="text/javascript">
var str = <?php echo json_encode($json); ?>;
document.getElementById('myImage').addEventListener(
'click',
function() {
foo(str);
}
);
</script>
Or something similer...
Only json_encode() is enough to escape the new line
echo "<img src=someimage.gif onclick=\"foo(".json_encode($newData).")\">";

Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
What is the easiest way to encode a PHP string for output to a JavaScript variable?
I have a PHP string which includes quotes and newlines. I need the contents of this string to be put into a JavaScript variable.
Normally, I would just construct my JavaScript in a PHP file, à la:
<script>
var myvar = "<?php echo $myVarValue;?>";
</script>
However, this doesn't work when $myVarValue contains quotes or newlines.
Expanding on someone else's answer:
<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>
Using json_encode() requires:
PHP 5.2.0 or greater
$myVarValue encoded as UTF-8 (or US-ASCII, of course)
Since UTF-8 supports full Unicode, it should be safe to convert on the fly.
Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.
encode it with JSON
function escapeJavaScriptText($string)
{
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
I have had a similar issue and understand that the following is the best solution:
<script>
var myvar = decodeURIComponent("<?php echo rawurlencode($myVarValue); ?>");
</script>
However, the link that micahwittman posted suggests that there are some minor encoding differences. PHP's rawurlencode() function is supposed to comply with RFC 1738, while there appear to have been no such effort with Javascript's decodeURIComponent().
The paranoid version: Escaping every single character.
function javascript_escape($str) {
$new_str = '';
$str_len = strlen($str);
for($i = 0; $i < $str_len; $i++) {
$new_str .= '\\x' . sprintf('%02x', ord(substr($str, $i, 1)));
}
return $new_str;
}
EDIT: The reason why json_encode() may not be appropriate is that sometimes, you need to prevent " to be generated, e.g.
<div onclick="alert(???)" />
<script>
var myVar = <?php echo json_encode($myVarValue); ?>;
</script>
or
<script>
var myVar = <?= json_encode($myVarValue) ?>;
</script>
Micah's solution below worked for me as the site I had to customise was not in UTF-8, so I could not use json; I'd vote it up but my rep isn't high enough.
function escapeJavaScriptText($string)
{
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
Don't run it though addslashes(); if you're in the context of the HTML page, the HTML parser can still see the </script> tag, even mid-string, and assume it's the end of the JavaScript:
<?php
$value = 'XXX</script><script>alert(document.cookie);</script>';
?>
<script type="text/javascript">
var foo = <?= json_encode($value) ?>; // Use this
var foo = '<?= addslashes($value) ?>'; // Avoid, allows XSS!
</script>
You can insert it into a hidden DIV, then assign the innerHTML of the DIV to your JavaScript variable. You don't have to worry about escaping anything. Just be sure not to put broken HTML in there.
You could try
<script type="text/javascript">
myvar = unescape('<?=rawurlencode($myvar)?>');
</script>
Don’t. Use Ajax, put it in data-* attributes in your HTML, or something else meaningful. Using inline scripts makes your pages bigger, and could be insecure or still allow users to ruin layout, unless…
… you make a safer function:
function inline_json_encode($obj) {
return str_replace('<!--', '<\!--', json_encode($obj));
}
htmlspecialchars
Description
string htmlspecialchars ( string $string [, int $quote_style [, string $charset [, bool $double_encode ]]] )
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.
This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application.
The translations performed are:
* '&' (ampersand) becomes '&'
* '"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
* ''' (single quote) becomes ''' only when ENT_QUOTES is set.
* '<' (less than) becomes '<'
* '>' (greater than) becomes '>'
http://ca.php.net/htmlspecialchars
I'm not sure if this is bad practice or no, but my team and I have been using a mixed html, JS, and php solution. We start with the PHP string we want to pull into a JS variable, lets call it:
$someString
Next we use in-page hidden form elements, and have their value set as the string:
<form id="pagePhpVars" method="post">
<input type="hidden" name="phpString1" id="phpString1" value="'.$someString.'" />
</form>
Then its a simple matter of defining a JS var through document.getElementById:
<script type="text/javascript" charset="UTF-8">
var moonUnitAlpha = document.getElementById('phpString1').value;
</script>
Now you can use the JS variable "moonUnitAlpha" anywhere you want to grab that PHP string value.
This seems to work really well for us. We'll see if it holds up to heavy use.
If you use a templating engine to construct your HTML then you can fill it with what ever you want!
Check out XTemplates.
It's a nice, open source, lightweight, template engine.
Your HTML/JS there would look like this:
<script>
var myvar = {$MyVarValue};
</script>

Categories