Passing Multi-line PHP variable to Javascript function - javascript

I'm trying to pass a PHP variable holding a text value (html content) read from SQL database to a Javascript function. I'm trying all different approaches such as json_encode(utf8_encode()) and preg_replace() but none of them seem to work.
Here's my code:
<?php
$db = new PDO('mysql:host=localhost;dbname=ramtin_data;charset=utf8', 'root', '');
foreach($db->query('SELECT * FROM posts') as $row)
{
$qtitle = $row['title'];
$qcontent = $row['content'];
$qpage = $row['page_id'];
$qcontent = json_encode(utf8_encode($qcontent));
echo "<script type='text/javascript'>
displayPost('$qtitle', '$qcontent');
</script>";
}
?>
Just want to mention that when I insert a row in my database with a simple line (including "and /) in the content field, the above code works.
I've also tried the following code and got the same result:
$qcontent = preg_replace('/\v+|\\\[rn]/','<br/>', $qcontent);
The value inside the content field in the database is the following string:
<img src="images/death_truck_titleDisplay.jpg" width="400" height="140" class="globalImageStyle" /><p class="postBodyContentParagraph">The work for another Construct2 game "Death Truck" has been started.</p><p class="postBodyContentParagraph">I've had the idea since a few weeks ago and I'm amazed that how much it had developed into better shapes and more complex gameplay ideas only through the first weeks that I've started working on the graphics and the game codes/logic.</p><p class="postBodyContentParagraph">I'm actually done with the truck and pedestrian graphics and movement codes (plus the interaction code between pedestrians and the truck) and have included the game in the projects page as a Work In Progress. You can check some of the graphics and the idea of the whole game (plus some gameplay ideas) in the projects page.</p>
How should I pass the above value to the displayPost() Javascript function?
UPDATE
The problem was with the single quotes inside the value. The accepted solution suggested all 's to be replaced with \' using $qcontent = str_replace("'", "\'", $qcontent); which worked perfectly.
The result however was quoted by json_encode() which I found the easiest way to remove the wrapping "s to be using content.slice(1, content.length - 2) (content is the second parameter which refers to $qcontent in the PHP section of the code) inside of the Javascript function.

Because you wrap your output in single quotes ' you need to escape those.
$qcontent = str_replace("'", "\'", $qcontent);

Related

PHP, requesting Javascript code in a PHP Echo [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 5 years ago.
So I need to request an image from a database, this then gets put in a variable, and gets called up in an echo.
However, i'm in a shortage of quotemarks in this case, seeing as the PHP echo uses double quotes, And then after calling up the onmouseover I use the single quotemarks, but after that I cannot use the double quotemarks again for the URL that gets caled up,
Going around this by putting the whole command in a variable didn't work.
Putting the whole command into the database didn't work.
Putting the command or url in a shorthand if statement didn't work.
And putting the Javascript code into a function, Also does not work.
Here is the code I'm talking about.
$afbeeldingurl = $row["afbeeldingurl"];
$overurl = $row["overafbeelding url"];
echo "<div><a href='../".$url.".html'><img onmouseover=mouseover() src='images/".$afbeeldingurl."' alt='' /></a>";
<script>
function mouseover()
{
this.src='images/<?php$overurl?>';
}
</script>
I thank you in advance :)
(Note, Only Javascript allowed, I cannot call up Jquery)
this.src='images/<?php$overurl?>';
Try switch this to
this.src='images/<?php echo $overurl; ?>';

PHP - file_get_contents get JSON with regex, but can't JSON decode (got JSON_ERROR_SYNTAX)

I try to parse this page : http://fr.hearthhead.com/cards to get the hearthstoneCards JS variable.
So i do something like this :
$url = 'http://fr.hearthhead.com/cards';
$content = file_get_contents($url);
preg_match('#var hearthstoneCards = (.*)}]\;#Us', $content, $out);
$out = $out[1].'}]';
$tab_id_card = json_decode($out,true);
I try every tricks i could find (trim, stripslashes, preg for BOM and other things, put flags on json_decode and many other things), but i didn't get this working.
If i file_put_contents the $out var and compare to the real source it's the same thing (same length). If i put the string on a JS console, i get the data. But PHP don't want to parse this var :(
Some one got an idea ? :)
The problem is that you assume that code is JSON, when it's really full-fledged JavaScript. Within that code, many unquoted repetitions of the property name popularity occur, which is fine JavaScript but invalid JSON.
I tried to build a regex to fix any unquoted property names. Problem is, it's infeasible. In my case, any colons inside values broke my regex.
Short of writing a parser to fix such nonconformities or invoking a JS interpreter (which would require an external dependency such as V8Js), I think you'll be fine with fixing this specific scenario for now:
$url = 'http://fr.hearthhead.com/cards';
$content = file_get_contents($url);
preg_match('#var hearthstoneCards = (.*)}]\;#Us', $content, $out);
$out = str_replace('popularity', '"popularity"', $out);
$out = $out[1].'}]';
$tab_id_card = json_decode($out,true);
If you worry about future introduction of new unquoted properties, you can check $tab_id_card for NULL and either log the error somewhere you routinely check or even go as far as somehow firing a notification for yourself. Although I'd do it, I'd say it's not a likely scenario, due to all the other properties being correctly quoted.

TextArea saving to MySQL with php and showing out in html

I want to save value in a textarea to MySQL database using PHP. And then I want to pass it to a variable in javascript
The value in a textare could be like this:
Hi I'm Son!!
Nice to meet you
So my 1st question is: How can I add the text to my database using php with the absence of special chars? (Like which encoding...)
I'm gonna pass that text through an event of a hyperlink click. It's something like this:
<?php
echo '<a href="#" onclick=passExample('$myText')>Something</a>';
?>
After all, the javascript I coded is like this:
function passExample(Exa){
$("#ExampleShow").empty();
var node = document.createElement("p");
if (Exa=='') Exa=' (No example)';
var textnode = document.createTextNode(html_entity_decode(Exa));
node.appendChild(textnode);
document.getElementById("ExampleShow").appendChild(node);
}
However, the result is not the way I wanted it to be. Line breaks are missing. And if I type some character like ''", it results in errors. How can I fix this?
echo '<a href="#" onclick="passExample(\''.addslashes($myText).'\')";>Something</a>';
also read:
What's the best method for sanitizing user input with PHP? (for clearing too much data from user input).
Pass a PHP string to a JavaScript variable (and escape newlines) (for using php output in javascript and escaping it).

How to obfuscate JavaScript on the server side?

I have a script I want to obfuscate or encrypt to hide from competition viewing the source code. I have found simple JS obfuscators but the issue with my script is I have PHP echoing variables into the JavaScript. The PHP is echoing strings and true/false.
Here is a piece of the JavaScript with PHP in it.
function redirect() {
var r = <?php echo $rvar; ?>;
if (r) {
window.location = prepare("<?php echo $redirect; ?>");
}
}
Can someone tell me what I can do to hide my JavaScript but be able to dynamically build the JS with PHP?
The only time I have ever wanted to obfuscate code is when I have been utterly ashamed of it. Retrospectively, I would probably obfuscate everything I have ever written. If protecting source is integral to your well-being, consider a shift to desktop programming.
Nevertheless, if there is one thing experience and memory has afforded me, it is that any serious newcomer to this field will stubbornly move forward with their own ideas, regardless of how bad it is, how much it grinds against commonsense and best practice, or how much a thread poo-poos all over the question. If you keep at it, hindsight will generously remind you of this period--cringes and all; the chastisements of a few strangers will pale in comparison, so I will give you one possible answer.
Use PHP's output buffering controls. You will want to start output buffering at the top of the script that will output all the JavaScript. This will capture everything into the buffer, which can then be assigned to a simple variable. This variable will contain everything that was supposed to be echoed out to the page immediately, but was instead captured and saved into the variable. This variable is just a regular string. Pass it to one of those JS obfuscators you found. This assumes it is done with PHP and is a PHP library for doing that. When it is obfuscated, echo it out. That is it. Here is an example:
<?php
// Start output buffering.
ob_start();
?>
function redirect() {
var r = <?php echo $rvar; ?>;
if (r) {
window.location = prepare("<?php echo $redirect; ?>");
}
}
<?php
// Get all the output captured in the buffer, and turn off output buffering.
// This will be a string.
$js_source = ob_get_flush();
// Obfuscate the $js_source string, by passing it to the obfuscator
// library you found.
$obfuscated_js_source = obfuscator5000($js_source);
// Send the source code to the browser by echoing it out.
echo $obfuscated_js_source;

Javascript: How to not directly post a variable

I am in need of help again, this time with a little Javascript snippet. There's also a little bit of PHP involved. The PHP is as follows (to generate random numbers)
$no1 = rand(0,9);
$no2 = rand(0,9);
$no3 = $no1+$no2;
I'm using this as a captcha method, for a very simple contact form. I'm not a fan of the bulky methods that I find all over google searches.
To validate this code, I use the following Javascript
if(document.forms["feedback"].check.value !== "<?php echo $no3; ?>"){
window.alert("Incorrect security code");
return false;
}
Then inside my form, I just use this:
<?php echo $no1; ?> + <?php echo $no2; ?> = <input name="check" type="text" id="check" size="3">
It all works as it's supposed to, but if there was a way for me to not to just directly echo $no3 in my javascript here:
if(document.forms["feedback"].check.value !== "<?php echo $no3; ?>")
Then that would eliminate any way of viewing the source to find the answer. I'm very much aware that it's a simple math problem, and if anyone knows how to view source, they most definitely can add, but a colleague of mine pretty much insisted on this.
So, does anyone know a way to help me out? I pretty much wrote most of this by hand, including the javascript, so please be nice when telling me that my code is horrible and out dated..
Thanks!
Put the $no1 and $no2 variables inside of span tags (or anything else you can directly target with Javascript) and then get the values from those spans with JS and use that to calculate the sum in JS rather than echoing it into the source with PHP, e.g. give the spans IDs like #captcha-1 and #captcha-2 use getElementByID to retrieve the values, then do the validation entirely in Javascript.
It will still be easy for anyone with a brain to figure out how to bypass but at least the answer will not be present anywhere in the source code other than as a JS variable.
If you want to hide the validation process entirely, you will need to use JS and AJAX to send the sum input by the user to a serverside PHP function which checks to see if it is equal to $no1 + $no2 and then submit the form as part of the response success function.
All that being said, this is still a very weak spam deterrent method.

Categories

Resources