PHP four levels of quotes - php

Is there any possible way to have four levels of quotes? Or a more efficient way to print javascript using PHP?
Here is the context for why I need four levels of quotes:
The first level is required to wrap around script to echo.
<?php echo '<script></script>';
The second level is required to wrap around html to print in java
<?php echo '<script>document.getElementByid("box").innerHTML = \'<button>test</button>\'</script>';
The third level is to wrap around onclick function in button
<?php echo '<script>document.getElementByid("box").innerHTML = \'<button onclick="some_function()">test</button>\'</script>';
The fourth level is to wrap around the parameters in the function
<?php echo '<script>document.getElementByid("box").innerHTML = \'<button onclick="some_function(*insert quote*parameter*insert quote*)">test</button>\'</script>';
Edit 1:
The entire script needs to be in echoed by php because in some scenarios the entire scripts needs to exist and other scenarios it needs to not exist e.g.
<?php if($variable == "do_not_print"){// do nothing}else{//echo script}

You can avoid string quoting problems by dropping out of the PHP context entirely and using
<?= ... ?>
to insert server-side values into the output.
json_encode() also helps sanitise values for safe use in a JavaScript context.
I also recommend using the DOM library for creating and inserting elements
For example
if ($someThingOrOther) :
// end PHP context
?>
<script>
(() => { // IIFE to avoid polluting the global scope
const someValueFromPhp = <?= json_encode($someValue) ?>
const button = document.createElement('button')
button.textContent = 'test'
button.addEventListener('click', () => {
some_function(someValueFromPhp)
}, false)
const box = document.getElementById('box')
// empty out "box", faster than using "innerHTML"
while(box.firstChild) {
box.removeChild(box.firstChild)
}
box.appendChild(button)
})()
</script>
<?php
// and now back to PHP
else:
?>
<script>
// ...
</script>
<?php
endif;

quote 1: ''
quote 2: ""
quote 3: \'\'
quote 4: \"\"
like this:
<div id="root"></div>
<?php
echo '<script type="text/javascript">
document.getElementById("root").innerHTML = "<button onclick=\"alert(\'its work\')\">test</button>\n";
</script>';
?>

Related

How to echo javascript code which contains php tags inside?

I usually echo script alert by simply
echo '<script type="text/javascript">alert("'.$my_message.'");</script>';
but how to echo the script when the script contains php tags? (see my example code)
Because of my php obfuscator script, I have to use only one <?php ?> tag. so in this case I need to echo the javascript without having <?php tags. What are the possible solutions in this case?
<?php
...some php code...
<script type="text/javascript">
jQuery(document).ready(function($){
$i = 0;
$('.wrapper_vertical_menu .megamenu_menu').append('<div class="more-wrap"><span class="more"><?php echo $this->__("More"); ?></span></div>');
$('.wrapper_vertical_menu .megamenu_menu > li.megamenu_lv1').each(function(){
$i ++;
if($i>13){
$(this).css('display', 'none');
}
});
... more js code ...
JavaScript doesn't "contain PHP tags". All your PHP code needs to do is build the resulting output string (which happens to be JavaScript code, but that doesn't matter to PHP) and echo it.
So where you have something like this:
echo "some javascript code <?php echo some_php_value; ?> more javascript code";
What you really want, quite simply, is this:
echo "some javascript code " . some_php_value . " more javascript code";
Don't try to nest <?php ?> tags within each other. Just concatenate the actual output you want and echo that output.

Javascript inside php not working properly

<div class="interactionLinksDiv">
REPLY
</div>
I have call the javascript function toggleReplyBox with five parameters. This code is written inside the php tags. But this code is not executing properly and the parameters are not being passed properly. If I call the function toggleReplyBox here with no parameters it works fine but thats not what I want.
<div class="interactionLinksDiv">
REPLY
</div>
When I copied this code to the html part of my php file It works fine and the parameters are passed and the function executes properly.
But I want to know why the function is not able to work inside of the php tags when everything is the same.
function toggleReplyBox(sendername,senderid,recName,recID,replyWipit) {
$("#recipientShow").text(recName);
document.replyForm.pm_sender_name.value = sendername;
document.replyForm.pmWipit.value = replyWipit;
document.replyForm.pm_sender_id.value = senderid;
document.replyForm.pm_rec_name.value = recName;
document.replyForm.pm_rec_id.value = recID;
document.replyForm.replyBtn.value = "Send";
if ($('#replyBox').is(":hidden")) {
$('#replyBox').fadeIn(1000);
} else {
$('#replyBox').hide();
}
}
Inside the php tags I changed the code :
print <<<HTML
<div class="interactionLinksDiv">
REPLY
</div>
HTML;
And it is still showing the error
Parse error: syntax error, unexpected T_VARIABLE in C:\xampp\htdocs\Fluid Solution\fluid-solution-website-template\interact\profile1.php on line 130
Line 130 is the <a href... line.
The first version of your code is neither PHP (javascript/HTML tags are "naked") nor Javascript: the "." string concatenation operator won't work in Javascript, nor will the $variable expansion.
You can get it to work in PHP like this:
<?php
$fullname = "Test";
$current_id = 15;
$id = 9;
$thisRandNum = 42;
// All lines beyond this point, and...
print <<<HTML
<div class="interactionLinksDiv">
<a href="javascript:toggleReplyBox('$fullname','$current_id',
'$current_id','$id','$thisRandNum')">REPLY</a>
</div>
HTML;
// ...up to here, start at the first column (i.e. they are not indented).
?>
Note that within the here-document (area between <<<HTML and HTML), you can't use the string concatenation operator "." (or any other).
Or you can do as you did in the second version of your code, replacing only the variables with <?php echo $variablename; ?> and leaving all the rest as HTML.
As a simpler example let's consider an alert() box with message sent from PHP. This means that:
1) the script is executed server side; anything between <?php ?> tags is executed, and its output replaces the tags themselves.
After this phase, we no longer have PHP but a mix of HTML and Javascript, which can be executed by the client it's sent to. So we want to have a HTML like
<script type="text/javascript">
alert('Hello, world');
</script>
To do this we can generate all the HTML in PHP:
echo '<script type="text/javascript">';
echo "alert('$message');"; // or also: echo 'alert("' . $message . '");';
echo '</script>';
Or we can do it with a here-document, where operators do not work, but $variables do:
echo <<<HEREDOCUMENT
<script type="text/javascript">
alert('$message');
</script>
HEREDOCUMENT;
Or we can run it all in HTML, and only rely on PHP to generate the lone variable:
<script type="text/javascript">
alert('<?php echo $message; ?>');
</script>
But always you need to keep separated what it's being done in PHP, what in Javascript, and what is in the HTML markup.

How to escape string from PHP for javascript?

lets imagine a form editor, it can edit available values. If the data contains " character (double quote) it "destroys" HTML code. I meant, lets check the code: so I generate HTML:
onclick="var a = prompt('New value: ', '<?php echo addslashes($rec[$i]); ?>'); if (a != null)....
and it results in
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
and this makes JS work impossible, so that it ruins the code. With single qoute ' it works OK. mysql real escape does the same.
How to escape any string so that it won't ruin javascript?
json_encode looked OK, but I must be doing something wrong, its still bad: heres a screenshot how Firefox sees it - it inserts a "bad" double quote! The value is just a simple number:
http://img402.imageshack.us/img402/5577/aaaahf.gif
and I did used:
('Ird be az új nevet:', <?php echo json_encode($rec['NAME']); ?>); if (a) {
The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:
<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';
That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
Your problem is highlighted in bold.
You can't quote a variable declaration
you shouldn't need to escape the double quote once this is removed since it is within single quotes.
Should look like this -
onclick="newFunc();"
<script>
function newFunc() {
var a = prompt('New value: ', 'aaaa"aaa');
if (a != null) { v....
}
</script>
...onclick="new_func();"...
<script>
function new_func() {
var a = prompt('new value:','<?php code; ?>');
if (a) { <!--javascript code--> } else { <!--javascript code--> }
}
</script>
I'm really just re-wording what #Marshall House says here, but:
In HTML, a double quote (") will always end an attribute, regardless of a backslash - so it sees: onclick="var a = prompt('New value: ', 'aaaa\". The solution that #Marshall offers is to separate your code out into a function. This way you can print escaped PHP into it without a problem.
E.g.:
<script>
// This is a function, wrapping your code to be called onclick.
function doOnClickStuff() {
// You should no longer need to escape your string. E.g.:
//var a = prompt('new value:','<?php echo $rec[$i]; ?>');
// Although the following could be safer
var a = prompt('new value:',<?php json_encode($rec[$i]); ?>);
if (a) { <!--javascript code--> }
else { <!--javascript code--> }
}
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->

PHP variable inside a javascript function

I'm attempting to put a php variable inside a javascript function and having no luck, here's what I got
<a class="code" href="javascript:void(0);"
onclick="javascript:if(window.dd && dd.elements)
d.elements.name1.moveTo(<? echo "$xpos"; ?>, <? echo "$ypos"; ?>);
return false;">
name1.moveTo(name1.x-20, name1.y+7);</a>
`
the moveTo() function works perfectly when I send it a javascript variable or simple numbers.
the reason its in a php variable at all is because I need the xpos to be inside a session variable to be accessed in other places. Afterwards I assign it as follows
$_SESSION['productcheck']['x'] = $xpos;
I'm kinda new to this, if you haven't already noticed, Thank you ahead of time :)
try not putting double quotes.
echo $xpos;
This is just to clarify, but you seem to have a typo (d should be dd). Corrected:
<a class="code" href="javascript:void(0);"
onclick="return (function () {
if(window.dd && dd.elements)
dd.elements.name1.moveTo(<? echo $xpos; ?>, <? echo $ypos; ?>);
return false;
})()"
>
name1.moveTo(name1.x-20, name1.y+7);
</a>
Some issues:
You don't need PHP variable interrpolation, $xpos by itself is fine
onclick should have only one expression that returns false, so you'd ideally wrap it in a function elsewhere. Here I used an anonymous one
Also, onclick need not start with 'javascript:, since it already is implicitly so.
My guess would that xpos and ypos are not in scope at the time that part of the page is processed.
Scope refers to the enclosing braces. for example the following will not work
$xpos = 100;
function printx(){
echo $xpos; // enclosing quotes not required
}
// call the function
printx();
Nothing will be printed
to fix it use the following
$xpos = 100;
function printx(){
global $xpos;
echo $xpos; // enclosing quotes not required
}
// call the function
printx();
this would then print 100

Can HTML be embedded inside PHP "if" statement?

I would like to embed HTML inside a PHP if statement, if it's even possible, because I'm thinking the HTML would appear before the PHP if statement is executed.
I'm trying to access a table in a database. I created a pulldown menu in HTML that lists all the tables in the database and once I select the table from the pulldown, I hit the submit button.
I use the isset function to see if the submit button has been pressed and run a loop in PHP to display the contents of the table in the database. So at this point I have the complete table but I want to run some more queries on this table. Hence the reason I'm trying to execute more HTML inside the if statement. Ultimately, I'm trying to either update (1 or more contents in a row or multiple rows) or delete (1 or more rows) contents in the table. What I'm trying to do is create another pulldown that corresponded to a column in a table to make the table search easier and radio buttons that correspond to whether I'd like to update or delete contents in the table.
<?php if($condition) : ?>
This will only display if $condition is true
<?php endif; ?>
By request, here's elseif and else (which you can also find in the docs)
<?php if($condition) : ?>
This will only display if $condition is true
<?php elseif($anotherCondition) : ?>
more html
<?php else : ?>
even more html
<?php endif; ?>
It's that simple.
The HTML will only be displayed if the condition is satisfied.
Yes,
<?php if ( $my_name == "someguy" ) { ?>
HTML GOES HERE
<?php } ?>
Yes.
<?php if ($my_name == 'someguy') { ?>
HTML_GOES_HERE
<?php } ?>
Using PHP close/open tags is not very good solution because of 2 reasons: you can't print PHP variables in plain HTML and it make your code very hard to read (the next code block starts with an end bracket }, but the reader has no idea what was before).
Better is to use heredoc syntax. It is the same concept as in other languages (like bash).
<?php
if ($condition) {
echo <<< END_OF_TEXT
<b>lots of html</b> <i>$variable</i>
lots of text...
many lines possible, with any indentation, until the closing delimiter...
END_OF_TEXT;
}
?>
END_OF_TEXT is your delimiter (it can be basically any text like EOF, EOT). Everything between is considered string by PHP as if it were in double quotes, so you can print variables, but you don't have to escape any quotes, so it very convenient for printing html attributes.
Note that the closing delimiter must begin on the start of the line and semicolon must be placed right after it with no other chars (END_OF_TEXT;).
Heredoc with behaviour of string in single quotes (') is called nowdoc. No parsing is done inside of nowdoc. You use it in the same way as heredoc, just you put the opening delimiter in single quotes - echo <<< 'END_OF_TEXT'.
So if condition equals the value you want then the php document will run "include"
and include will add that document to the current window
for example:
`
<?php
$isARequest = true;
if ($isARequest){include('request.html');}/*So because $isARequest is true then it will include request.html but if its not a request then it will insert isNotARequest;*/
else if (!$isARequest) {include('isNotARequest.html')}
?>
`
<?php if ($my_name == 'aboutme') { ?>
HTML_GOES_HERE
<?php } ?>
I know this is an old post, but I really hate that there is only one answer here that suggests not mixing html and php. Instead of mixing content one should use template systems, or create a basic template system themselves.
In the php
<?php
$var1 = 'Alice'; $var2 = 'apples'; $var3 = 'lunch'; $var4 = 'Bob';
if ($var1 == 'Alice') {
$html = file_get_contents('/path/to/file.html'); //get the html template
$template_placeholders = array('##variable1##', '##variable2##', '##variable3##', '##variable4##'); // variable placeholders inside the template
$template_replace_variables = array($var1, $var2, $var3, $var4); // the variables to pass to the template
$html_output = str_replace($template_placeholders, $template_replace_variables, $html); // replace the placeholders with the actual variable values.
}
echo $html_output;
?>
In the html (/path/to/file.html)
<p>##variable1## ate ##variable2## for ##variable3## with ##variable4##.</p>
The output of this would be:
Alice ate apples for lunch with Bob.

Categories