Mix the html and php variables in an echo statement

This may be a problem of my trouble with using single and double quotes in one statement. But I have this piece of code:

echo '

The problem with this is that the submit button says the phrase $number
instead of the value of that variable.

So I looked around and found this solution:

echo "

This outputs the value of $number correctly, but I am used to using single quotes around my echo statements and would like to keep it that way. Why does just switching all single quotes into doubles, and doubles into singles fix the problem? And is there a modification to the first bit of code that would allow me to keep the single quotes on echo, and double quotes on the attributes?

In PHP, double quoted strings are automatically parsed for any variables contained within, but single quoted strings are not. Therefore:

$myVar = 21;
echo "myVar: $myVar"

This outputs the text: myVar: 21


$myVar = 21;
echo 'myVar: $myVar'

This outputs the text: myVar: $myVar

One problem with your code is that in HTML, the values of elements’ attributes must be enclosed in double quotes, not single quotes. I know that some browsers will accept this form (or even no quotes at all), but this is not the correct method.

There are various ways of achieving what you wish, correctly.

Method one: Escaping double-quoted strings:

$myVar = 21;
echo "

While this may be a rather inelegant solution, it will work.

Method two: Using string concatenation with single (or double) quoted strings:

$myVar = 21;
echo '

This offers a better solution IMO because you can use function calls or any other PHP code in there if you wish.


Please note that when you aren’t certain of the contents of $myVar
(i.e. the user enters it in), putting it directly into HTML code is a security vulnerability in the form of cross-site scripting (XSS). Imagine the user enters something like this:

<div id="lol2

This will cause the resulting HTML code to contain the following:


This is just a benign example, but an attacker could easily use the same technique to steal a user’s cookies (to pretend to be logged in as that user). The message here is that when you aren’t 100% sure of the contents of a variable, don’t insert it into HTML code directly. Instead, call htmlspecialchars($myVar)
. This would translate to the following:

$myVar = $_POST['whatever'];
echo '
Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Mix the html and php variables in an echo statement

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录