Best way to escape single quotes

This apparently is the wrong way:

$popupContent .= "<input name='senderFirstName' type='hidden' value='{$_SESSION['firstName']}'>";

Suggestions?

Don’t jumble the PHP and HTML together - then you will not need to escape quotes.

I don’t use it much but it can be quite useful to use ‘heredoc’

Then you don’t have to escape anything.

But if you did want to escape the above i’d prob do …
$popupContent .= "<input name='senderFirstName' type='hidden' value='". $_SESSION['firstName'] ."'>";

Although normally use single quotes $content = 'something'; but i think that is just the way i like it. Double quotes though can actually execute the variable though so you could do something like

$firstName = $_SESSION['firstName']; $popupContent .= "<input name='senderFirstName' type='hidden' value='$firstName'>";

which would sort the problem with escaping the single quotes in the session variable.

hth

There is nothing to escape in your example.
This apparently is the right way to address the array element with a string key inside of a quoted string. Dunno why do you think otherwise.

If you like, you can omit single quotes in this case at all

$popupContent .= "<input name='name' type='hidden' value='$_SESSION[firstName]'>";

but still, there is no “right” or “wrong” way. Everything is right which is allowed by the syntax rules.

Note that your code is a subject of a texbook XSS injection

I prefer concatenation because an error is thrown if the variable does not exist.

$popupContent .= '<input name='name' type='hidden' value="' 
       ._SESSION['firstName'] . '">';

Also works well for images.

often sprintf() allows for more clarity in the code

$popupContent .= sprintf("<input name='name' type='hidden' value='%s'>", $_SESSION['firstName']);

Undefined variable error is irrelevant to this question. It’s thrown every time you’re trying to access a non-existent variable, no matter which syntax you are using.

The concern on html output is that you need to escape certain html characters such as <>& as well as quotes. So pretty much any content going out should be escaped. I am also a heredoc fan:

function escape($content)
{
    return htmlspecialchars($content, ENT_COMPAT);
}
$firstName = "Bill & Ted";

$firstNameEscaped = escape($firstName);

$popupContent = <<<EOT
  <input name="senderFirstName" type="hidden" value="{$firstNameEscaped}">
EOT;

echo $popupContent;

// Result
<input name="senderFirstName" type="hidden" value="Bill &amp; Ted">

I cannot test at the moment because using a tablet.

Try declaring the variable inside double quotations and see if a non-existent variable throws an error.

Just tested on my desktop and I was wrong :frowning:

An error is thrown when an undeclared variable is enclosed in double quotes.

Please accept my apologies.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.