How do I escape single quotes in PHP [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm working with Magento trying to style error messages as pop-ups, instead of displaying inline.
I found an article explaining how to do this, but the code displays an error when I try to use it. (http://azharkamar.com/5378/magento-modifying-default-message-alert-box-popup-dialog/)
This is the code I am using:
$html .= '<a class="msgclose" href="#" onclick="document.getElementById("messages").style.visibility="hidden"">x</a>';
A comment mentioned after the article said that they "had to escape the single quotes to make it work."
I tried editing the code, and used the code shown below. The close button appears but it won't close the box.
$html .= '<a class="msgclose" href="#" onclick="document.getElementById("messages").style.visibility="hidden"">x</a>';
Any help would be much appreciated, thank you!

You can escape a single quote by preceeding it with a backslash, or by using double quotes for the string:
$var = 'Escape \' like this';
$var = "Or embed ' like this";
If you need to embed javascript, it might be a bit harder, because the quote in the Javascript string needs also to be escaped. Usually you can get arround by cleverly combining single and double quotes:
$html .= '<a class="msgclose" href="#" onclick="document.getElementById(\'messages\').style.visibility=\'hidden\'">x</a>';
Or you can use heredoc:
$html = <<<html
<a class="msgclose" href="#" onclick="document.getElementById('messages').style.visibility='hidden'">x</a>'
html;
By the way, escaping quotes in HTML is a different story. You use the " entity for that, so if you want to have double quotes in Javascript, the result would be:
$html .= '<a class="msgclose" href="#" onclick="document.getElementById("messages").style.visibility="hidden"">x</a>';

You can escape the single quotes in your code, with backslashes, like this:
$html .= '<a class="msgclose" href="#" onclick="document.getElementById(\'messages\').style.visibility=\'hidden\'">x</a>';
Or you can move the javascript out of your html:
$html .= '<a class="msgclose" href="#" onclick="hideMessage()">x</a>';
<script type="text/javascript">
function hideMessage() {
document.getElementById("messages").style.visibility = "hidden";
}
</script>

You can both escape ' putting backslashes before them (' -> \')
$html .= '<a class="msgclose" href="#" onclick="document.getElementById(\'messages\').style.visibility="hidden">x</a>';
Or use the EOF function to eliminate the need for escaping.
$html .= <<<EOF
<a class="msgclose" href="#" onclick="document.getElementById('messages').style.visibility="hidden">x</a>
EOF;

To Escape a character in php use \ backslash . But the value that $html will have after escaping it will be untidy
Here is how i would do it..
$html .= "<a class='msgclose' href='#' onclick='document.getElementById('messages').style.visibility='hidden''>x</a>";
I used double quotes and within them i used single quotes

Related

window.open not working parse URL truncated

I'm trying to get a link to open as a new window in PHP, I tried the following and a few variations, yet for some reason the links stops in javascript:void(window.open(
Any idea? Could it be something wrong with the '""'?
$html .= '<a class="ficha_partido_popup" href="javascript:void(window.open("/servicios/deporte/partidos/fichapartido_'.$filaPartido["partidocod"].'.html"))" rel="nofollow" title="Ver Ficha del partido"><img src="/imagenes/ficha.png" alt="Ver la ficha del partido" /></a>';
You need to escape the double quotes:
$html .= '<a class="ficha_partido_popup" href="javascript:void(window.open(\"/servicios/deporte/partidos/fichapartido_'.$filaPartido["partidocod"].'.html\"))" rel="nofollow" title="Ver Ficha del partido"><img src="/imagenes/ficha.png" alt="Ver la ficha del partido" /></a>';
You're using ' (single quote) to create the string in PHP.
You're using " (double quote) to create the string in Javascript.
Now, you're saying href="...window.open("...")". The issue is that you're trying to nest " within " and that just breaks it all. So the first double quote inside window.open ends up being the closing double quote for href and the rest of the string just becomes invalid in javascript.
To fix this, you can replace nested double quotes with single quotes and say href="...window.open('...')", except that you can't since if you use single quotes here, you'll end up breaking things in PHP since you're using single quotes to form the string in PHP.
So, use single nested quotes but escape them, like this -
href="...window.open(\'...\')"
So, your code will now become -
$html .= '<a class="ficha_partido_popup" href="javascript:void(window.open(\'/servicios/deporte/partidos/fichapartido_'.$filaPartido["partidocod"].'.html\'))" rel="nofollow" title="Ver Ficha del partido"><img src="/imagenes/ficha.png" alt="Ver la ficha del partido" /></a>';
To make it simple, divide it into 2 lines
$window_link = 'window.open("/file_path/filename_'.$filaPartido["partidocod"].'.html")';
$html .= '<a href="javascript:void( ' . $window_link . ' )" >Any link</a>';
OR
$link = $filaPartido["partidocod"];
$html .= <<<HTML
<a href="javascript:void( window.open('/file_path/filename_{$link}.html') )" >Any link</a>
HTML;

Onlick doesn't work

I'm newbie in programming. I would like to open a link by using onclick event but this doesn't work....Can you help me please?
Here the code:
$content .= '<a class="mike-link mike-pinterest"
href="'.$pinterestURL.'" data-pin-custom="true" target="_blank"
onclick="window.open("", "mikewindow","menubar=1,resizable=1,width=350,height=250");
return false;">Pin It</a>' ;
I think what you are trying to achieve is the following:
$content .= '<a class="mike-link mike-pinterest"
href="javascript:window.open("'.$pinterestURL.'", "mikewindow","menubar=1,resizable=1,width=350,height=250");
return false;" data-pin-custom="true" target="_blank"
>Pin It</a>' ;
onclick="window.open("", "mikewindow","menubar=1,resizable=1,width=350,height=250");
Your first " starts the attribute value.
Then you say window.open( which is the attribute value.
Then you say " which marks the end of the attribute value.
Then you say " again, which is invalid HTML.
If you want to include a " as data in an HTML attribute delimited with " characters then you need to encode it as "
Try this:
$content .= '<a class="mike-link mike-pinterest"
href="' . $pinterestURL . '" data-pin-custom="true" target="_blank"
onclick="window.open(\'\', \'mikewindow\',\'menubar=1,resizable=1,width=350,height=250\');
return false;">Pin It</a>';
Your problem was that you used double quotes to open the onclick, but then double quotes again inside the window.open function, which instead closed the onclick action quotes. The tricky thing is that using single quotes will close your php quotes. So what you do is use \', which lets php ignore the single quote, and write it as a single quote in your html.
Check this this codepen link:
<p>Click Me!</p>
$('p').click(function(){
window.open('https://google.com');
});
https://codepen.io/anon/pen/ZjRbEW

How can I use window.open in my string echo'd from PHP?

Through a $_POST request I query a database and return info in a string as follows:
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> watch full tutorial</div>';
My problem is the "window.open" statement. It works as follows in a plain html doc as inline JS:
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> watch full tutorial</div>';
But I think my problem in the PHP string is the single and double quotation marks.What am I doing wrong?
You need quotes around the URL.
$output .= '... <a href="#" onclick="window.open("' . $prev . '", "_blank", ...
// ---------------------------------------- here ^ -- and here ^
You would be able to notice this pretty quick if you looked at your HTML source, to see what was generated.
It seems that you've messed up the quotes in there slightly...
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> watch full tutorial</div>';
You used " to define the onclick event, however you've used " inside of that event, which made it invalid. Replace the " inside of the event with \', which will escape the quote and not mess up your PHP.
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> watch full tutorial</div>';
And, if $prev is not referring to a variable in JS (if it will end up as a string), you need those quotes around that as well.
\''.$prev.'\'

how can i use ' and " in a code in PHP and Javascript?

I'd like how i can use a lot of ' and " in a code.
Example:
echo 'document.write("<a href='$url'> <img src='{$row["image"]}' border='0' /> </a>");';
I tried but i'm getting error. Anyone can help?
so, you have multi-level problem here:
data which is echoed to html, usually should be properly escaped via htmlspecialchars
you want to see document.write("..."..."); in your finally produced html, this will trigger javascript syntax error
to avoid this error, you should use \ before " inside string
echo 'document.write("<img src=\"' . htmlspecialchars($row["image"]) . '\" border=\"0\" />");';
note: I'm using echo with single quotes, if you're using double quotes - you will have to double \\
in case of double quotes your code will look like:
echo "document.write(\"<img src=\\\"" . htmlspecialchars($row["image"]) . "\\\" border=\\\"0\\\" />\");";
Here are three ways to tackle this problem.
1. Escaping the inner double slashes
echo "document.write(' <img src=\"{$row['image']}\" border=\"0\" /> ');";
2. Closing your PHP tags and writing javascript
?>
document.write(' <img src="<?php echo $row['image']; ?>" border="0" /> ');
<?php
3. Using Heredoc syntax
echo <<<EOJS
document.write(' <img src="{$row['image']}" border="0" /> ');
EOJS;
This will work:
<?php
$url = "http://www.google.com";
$row = array("image" => "image.png");
echo "document.write(' <img src=\"".$row["image"]."\" border=0 /> ');";
// output: document.write(' <img src="image.png" border=0 /> ');
?>
You can use the heredoc syntax:
echo <<<EOT
document.write(<a href='{$url}'> <img src='{$row["image"]}' border='0' /> </a>);
EOT;
From phpdocs
Heredoc text behaves just like a double-quoted string, without the
double quotes. This means that quotes in a heredoc do not need to be
escaped, but the escape codes listed above can still be used.
Variables are expanded, but the same care must be taken when
expressing complex variables inside a heredoc as with strings.
Also note, that
It is very important to note that the line with the closing identifier
must contain no other characters, except a semicolon (;). That means
especially that the identifier may not be indented, and there may not
be any spaces or tabs before or after the semicolon. It's also
important to realize that the first character before the closing
identifier must be a newline as defined by the local operating system.
This is \n on UNIX systems, including Mac OS X. The closing delimiter
must also be followed by a newline.

Javascript function inside ahref not working in php echo [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a series of images/links that is calling a javascript function when the image is clicked. The code below works fine in regular html, but when I try to use this inside of a php echo it doesn't work.
echo "<a href='javascript:nfllogin('nflshow');' class='black' style='font-size:12px;'><img src='images/nfl-button-index.jpg' width='177' height='145' alt=''/></a> ";
Everything appears fine but when I click the image/link it doesn't pull up the div area I am expecting to see. How can I make this work?
You'll need to escape some of the quotes to avoid nested quotes of the same type.
echo "<a href='javascript:nfllogin(\"nflshow\");' class='black' style='font-size:12px;'><img src='images/nfl-button-index.jpg' width='177' height='145' alt=''/></a> ";
Will actually output:
<a href='javascript:nfllogin("nflshow");' class='black' style='font-size:12px;'><img src='images/nfl-button-index.jpg' width='177' height='145' alt=''/></a>
Which should work better for you.
echo '<img src="images/nfl-button-index.jpg" width="177" height="145" alt=""/>';
a good practice in echoing html in php is use single quote to echo and double quotes thereafter. This save the stress of escaping string. Try the above pls.
if it doesnt respond change this: javascript:nfllogin("nflshow");
The first thing that hits my eyes is that there's a problem with single and double quotes.
echo '<a href="javascript:nfllogin(\'nflshow\');" ';
echo "class='black' style='font-size:12px;'><img src='images/nfl-button-index.jpg' width='177' height='145' alt=''/></a> ";
Since the JavaScript contains a single quote, you have to put the href into double quotes. I split the echo in two to avoid to escape quotes with backslashes.
To echo such big chunks of html, the heredoc syntax comes in handy too. This would look like:
echo <<<EOT
<a href="javascript:nfllogin(\'nflshow\');" class="black" style="font-size:12px;">
<img src="images/nfl-button-index.jpg" width="177" height="145" alt=""/>
</a>
EOT;
There are two advantages:
There's no need to escape quotes
As a consequence, you can indent your HTML code and use double quotes for the attributes. It's just a matter of clean code to quote all HTML code consistently with double quotes.

Categories