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')" );
Related
I am trying to display my images in a HTML table but for some reason they just won't show up.
The images are located in a separate folder called 'images' and the image name is stored in my database as a varchar named e.g., filename.jpg
In my overview page I use this as my code:
<!DOCTYPE html>
<html lang="en">
<body>
<table>
<?php
foreach ($objectname as $key) {
echo '<tr><td><img src="images/' . $key->getImage() . '"></td></tr>';
}
?>
</table>
</body>
</html>
Hoping someone here can point me in the right direction :) thanks!!
You should first print print_r ($objectname), check if it comes with data and what its attributes are to see which one you need to occupy.
Second the $ key->getImage() getImage () = function () you are calling a function.
I think you should change the getImage() function in your html to the name of the field in the database as follows:
$key->getImage() to $key->Image_field_name_in_the_database
Because the name of the image (e.g: filename.jpg) is saved in a field of a table in your database.
Image_field_name_in_the_database will be the name of the field that contains the name of the image in the database.
Having the next PHP code that produce HTML code:
(simplified function, the real one on same idea but longer with loops and so on):
<?php
function show_doc_html() {
$text_to_title = "some text from db";
?>
<html>
<head>
<title>
<?php echo $text_to_title ?>
</title>
</head>
<body>
</body>
</html>
<?
}
I would like to return a PDF to the user, without changing too much of this code. we are working under drupal so we have function that can get html string and convert it to pdf, but the former function doesn't return anything but printing to stdout. Id it possible? or should i rebuild the old function to return string?
Is that what you need?
I have used it in my project. You can just write your markup and inline css in node template using view_mode = 'PDF'
The easiest way was to encapsulate my function with "ob_start()" get all text using "ob_get_contents()", then convert it to pdf.
Something like:
function show_doc_pdf() {
ob_start();
function show_doc_html() ;
$html_var = ob_get_contents();
ob_end_clean();
//use wkhtmltopdf api on $html_var to return pdf
}
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.
I'm trying to echo a PHP tag by doing this:
echo "<?php echo \"test\"; ?>";
The result should be just "test" without quotes, but my code isn't working. What is happening is that nothing is shown on the page, but the source code is "<?php echo "teste"; ?>"
Most of you will want to know why I want to do this. I'm trying to make my own template system; the simplest way is just using file_get_contents and replacing what I want with str_replace and then using echo.
The problem is, that in the template file, I have to have some PHP functions that doesn't work when I echo the page, is there another simple way to do this? Or if you just answer my question will help a lot!
Here is an example of what I am trying to accomplish:
template.tpl:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>[__TITULO__]</title>
</head>
<body >
<p>Nome: [__NOME__] <br />
Email: [__EMAIL__]<br />
<?php
if ($cidade != "") {?>
Cidade: [__CIDADE__]<br />
<?php
}
?>
Telefone: ([__DDD__]) [__TELEFONE__] <br />
Fax:
([__DDDFAX__]) [__FAX__] <br />
Interesse: [__INTERESSE__]<br />
Mensagem:
[__MENSAGEM__] </p>
</body>
</html>
index.php
<?php
$cidade = "Teste";
$file = file_get_contents('template.php');
$file = str_replace("[__TITULO__]","Esse Título é téste!", $file);
$file = str_replace("[__NOME__]","Cárlos", $file);
$file = str_replace("[__EMAIL__]","moura.kadu#gmail.com", $file);
if ($cidade != "") {
$file = str_replace("[__CIDADE__]",$cidade, $file);
}
echo $file;
?>
I can solve all this just not showing the div that has no content. like if i have a template, and in it i have 2 divs:
<div id="content1">[__content1__]</div>
<div id="content2">[__content2__]</div>
if the time that i set the content to replace the template I set the content1 and not set content 2 the div content2 will not show...
Use htmlspecialchars
That will convert the < > to < and >
You are dealing with two sets of source code here that should never be confused - the server code (PHP, which is whatever is in the <?php ?> tags) and the client (or browser) code which includes all HTML tags. The output of the server code is itself code that gets sent to the browser. Here you are in fact successfully echoing a PHP tag, but it is meaningless to the browser, which is why the browser ignores it and doesn't show anything unless you look at the client code that got sent to it.
To implement templates in this style, either they should not have any PHP code, or the resulting string (which you have stored in $file) should itself be executed as though it were PHP, rather than echoing it straight to the client. There are various ways to do this. One is to parse out the PHP tags in the string, echo everything that is not within the PHP tags and run eval() on everything that is.
Say you have a PHP variable called $description with the following value (that contains quotes and line breaks):
Tromp L'oeil Sheath Dress
You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.
You want to pass the contents of this variable into a Javascript function that writes that value into an INPUT of type text.
How would you do this? I tried this:
$description = htmlspecialchars ( $product->description, ENT_QUOTES );
However, I get a JS error. I also tried this:
$description = rawurlencode ( $product->description );
This encodes the value like so:
Michael%20Kors%0A%0ATromp%20L%27oeil%20Sheath%20Dress%0A%0AYou%20will%20certainly%20%22trick%20the%20ey%22%20of%20many%20in%20this%20gorgeous%20illusion.%20Add%20it%20to%20your%20fall%20wardrobe%20before%20it%20disappears.%0A%0AAvailable%20in%20Black%2FNude
This value can be passed as a JS variable, but I don't know of a JS function that will cleanly reverse a PHP rawurlencode.
Is there a matching pair of functions that I could use to encode a variable in PHP to allow it to be passed into a JS function -- and then reverse the encoding in JS so that I get the original value of the PHP variable?
EDIT: To clarify the question and reply to comments, here is some test code:
<?php
$str =<<<EOT
Tromp L'oeil Sheath Dress
You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.
EOT;
echo 'here is the string: <pre>' . $str . '</pre>';
?>
<script type="text/javascript">
<?php
// this does not work with JS as i get an unterminated string literal if i just use addslashes in the following commented-out line
// echo 'alert(\'' . addslashes($str) . '\');';
// this works with JS (the alert activates) but how do i un-rawurlencode in JS?
// echo 'alert(\'' . rawurlencode($str) . '\');';
// this does not work with JS, because of the line breaks
echo 'alert(\'' . htmlspecialchars ($str, ENT_QUOTES) . '\');';
?>
</script>
simplest would be to use json_encode()
I ran into problems using some of the answers proposed here, including issues with line breaks and decoding certain html entitites like /. I ended up using rawurlencode (in PHP) and decodeURIComponent (in Javascript) as matching functions to encode/decode the string so it could be passed as a JS variable. Here is working code for anybody else running into this problem.
<?php
$str =<<<EOT
Tromp L'oeil Sheath Dress
You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.
Available in Black/Nude
EOT;
echo 'here is the string: <pre>' . $str . '</pre>';
?>
<p>below is the variable doc.write'd after being rawurlencod'ed in PHP then decodeURIComponent'ed in JS:</p>
<script type="text/javascript">
<?php
echo 'document.write(decodeURIComponent("'. rawurlencode($str).'"));';
?>
You can use json_encode if available. It encodes the string according to the JSON data format that is a subset of JavaScript; so any JSON is also valid JavaScript.
<script type="text/javascript">
<?php
echo 'alert('. json_encode($str).');';
?>
</script>
Otherwise try PHP’s rawurlencode and decode it with JavaScript’s decodeURI:
<script type="text/javascript">
<?php
echo 'alert(decodeURI("'. rawurlencode($str).'"));';
?>
</script>
Json is the solution.
See sample code
Two pages to demonstrate
First Page json.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
// This is more like it!
$('#submit').live('click', function() {
var id=$("#id").attr("value");
$.getJSON("json-call.php", {id:id}, function callback(data) {
$("#list").html("var1:"+data['var1']+"<br/>"+"var2:"+data['var2']+"<br />id:"+data['id']);
});
});
});
</script>
<input id="id" type="text" value="test value" />
<input type="button" id="submit" value="submit" />
<div id="list"></div>
</body>
</html>
Second Page json-call.php
$var1 = 'your name';
$var2 = 'your address';
$id = $_REQUEST['id'];
print(json_encode(array ('var1' => $var1, 'var2' => $var2, 'id'=>$id)));
and Results
var1:your name
var2:your address
id:test value
Not sure whether json_decode does everything you need. htmlspecialchars() and htmlspecialchars_decode() should do the trick for everything but the line breaks. The line breaks are kind of a pain, since the combination of linebreaks and carriage returns will depend on the browser, but I think something like this should work:
$value = "your string with quotes and newlines in it.";
//take cares of quotes
$js_value = htmlspecialchars($value);
//first line replaces an ASCII newline with a JavaScript newline
$js_value = str_replace("\n",'\n',$js_value);
//second line replaces an ASCII carriage return with nothing, so you don't get duplicates
$js_value = str_replace("\r",'',$js_value);
//reverse to convert it back to PHP
$php_value = str_replace('\n',"\r\n",$js_value);
$php_value = htmlspecialchars_decode($php_value);
Maybe not the most elegant solution, but that's not really my specialty. ;) Also, keep in mind that newline characters will just end up like spaces in an <input type="text"> field.
Here is a litle something I have made:
function safefor_js($str) {
return str_replace(array("'",'"',"\n"), array('\x22','\x27','\\n'), $str);
}