82

I am writing some JavaScript code that uses a string rendered with PHP. How can I escape single quotes (and only single quotes) in my PHP string?

<script type="text/javascript">
    $('#myElement').html('say hello to <?php echo $mystringWithSingleQuotes ?>');
</script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andrew
  • 227,796
  • 193
  • 515
  • 708
  • 8
    You'll need to escape more than single quotes. Newlines, for one. You might do well with something like `addcslashes($mystringWithSingleQuotes, "'\"\r\n\\\t\0..\37")` – Frank Farmer Jun 07 '11 at 17:27
  • 2
    Instead of handling the escaping yourself, use `json_encode()` to get a valid Javascript string (and remove your outer single quotes). – mario Jun 07 '11 at 17:29
  • 1
    @Frank: Can you post your answer as an answer instead of as a comment? Proper answers in comments can not be selected and therefore creates fake "unanswered questions". – Sylverdrag Jun 07 '11 at 17:33
  • Why can't you just double quotes in `.html()` instead of wrapping in single quotes? the php expansion will happen regardless. Been doing this for everything from attributes on elements and imports as well as variable assignments inside script blocks. – Mark Carpenter Jr Apr 06 '18 at 16:34

11 Answers11

69

Quite simply: echo str_replace('\'', '\\\'', $myString); However, I'd suggest use of JSON and json_encode() function as it will be more reliable (quotes new lines for instance):

<?php $data = array('myString' => '...'); ?>

<script>
   var phpData = <?php echo json_encode($data) ?>;
   alert(phpData.myString);
</script>
Justin
  • 26,443
  • 16
  • 111
  • 128
Crozin
  • 43,890
  • 13
  • 88
  • 135
  • 1
    Thank you.. I knew this but I was facing problem because I was trying to do `JSON.parse('');` and it was failing because there was a single quote inside data. Later I came to know there is no need to use `JSON.parse` here. – Ravi Dhoriya ツ Jan 16 '15 at 12:00
  • 6
    All of the answers that say `str_replace("'","\\'", $string)` and similar are incorrect. Consider the string \' It will be replaced with \\' and this will cause an injection vulnerability. Instead use json_encode as Crozin suggests. – David M. Oct 11 '12 at 00:50
  • json_encode could get you into trouble if the json extension was not installed. Read my solution below using strtr(..) – Basil Musa Nov 19 '15 at 15:21
  • 2
    @BasilMusa As of PHP 5.2 JSON extension is bundled by default ([source](http://php.net/manual/en/json.installation.php)) so I wouldn't be worried about that. – Crozin Nov 19 '15 at 15:43
  • 1
    @DavidM. except that the OP never mentions JSON and was very specific about what he needs. – Julian Sep 10 '16 at 22:03
  • Perfect! I was looking for that because I had to return a string from PHP to JS, and this was just the way to go. THank you! – Adam Sep 10 '18 at 05:40
40

If you want to escape characters with a \, you have addcslashes(). For example, if you want to escape only single quotes like the question, you can do:

echo addcslashes($value, "'");

And if you want to escape ', ", \, and nul (the byte null), you can use addslashes():

echo addslashes($value);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PhoneixS
  • 10,574
  • 6
  • 57
  • 73
  • 1
    Thanks for pointing out [addcslashes](http://php.net/manual/en/function.addcslashes.php) to escape arbitrary characters. – Avatar Apr 30 '17 at 15:31
20
str_replace("'", "\'", $mystringWithSingleQuotes);
Julian
  • 8,808
  • 8
  • 51
  • 90
18

In some cases, I just convert it into ENTITIES:

                        // i.e.,  $x= ABC\DEFGH'IJKL
$x = str_ireplace("'",  "&apos;", $x);
$x = str_ireplace("\\", "&bsol;", $x);
$x = str_ireplace('"',  "&quot;", $x);

On the HTML page, the visual output is the same:

ABC\DEFGH'IJKL

However, it is sanitized in source.

T.Todua
  • 53,146
  • 19
  • 236
  • 237
10

Use the native function htmlspecialchars. It will escape from all special character. If you want to escape from a quote specifically, use with ENT_COMPAT or ENT_QUOTES. Here is the example:

$str = "Jane & 'Tarzan'";
echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotes
echo "<br>";

echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes
echo "<br>";

echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes

The output would be like this:

Jane &amp; 'Tarzan'<br>
Jane &amp; &#039;Tarzan&#039;<br>
Jane &amp; 'Tarzan'

Read more in PHP htmlspecialchars() Function

Nishad Up
  • 3,457
  • 1
  • 28
  • 32
8

To replace only single quotes, use this simple statement:

$string = str_replace("'", "\\'", $string);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
7

You can use the addcslashes function to get this done like so:

echo addcslashes($text, "'\\");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Junior
  • 11,602
  • 27
  • 106
  • 212
2

After a long time fighting with this problem, I think I have found a better solution.

The combination of two functions makes it possible to escape a string to use as HTML.

One, to escape double quote if you use the string inside a JavaScript function call; and a second one to escape the single quote, avoiding those simple quotes that go around the argument.

Solution:

mysql_real_escape_string(htmlspecialchars($string))

Solve:

  • a PHP line created to call a JavaScript function like

echo 'onclick="javascript_function(\'' . mysql_real_escape_string(htmlspecialchars($string))"

arturocu81
  • 21
  • 3
1

I wrote the following function. It replaces the following:

Single quote ['] with a slash and a single quote [\'].

Backslash [\] with two backslashes [\\]

function escapePhpString($target) {
    $replacements = array(
            "'" => '\\\'',
            "\\" => '\\\\'
    );
    return strtr($target, $replacements);
}

You can modify it to add or remove character replacements in the $replacements array. For example, to replace \r\n, it becomes "\r\n" => "\r\n" and "\n" => "\n".

/**
 * With new line replacements too
 */
function escapePhpString($target) {
    $replacements = array(
            "'" => '\\\'',
            "\\" => '\\\\',
            "\r\n" => "\\r\\n",
            "\n" => "\\n"
    );
    return strtr($target, $replacements);
}

The neat feature about strtr is that it will prefer long replacements.

Example, "Cool\r\nFeature" will escape \r\n rather than escaping \n along.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Basil Musa
  • 8,198
  • 6
  • 64
  • 63
0

I am not sure what exactly you are doing with your data, but you could always try:

$string = str_replace("'", "%27", $string);

I use this whenever strings are sent to a database for storage.

%27 is the encoding for the ' character, and it also helps to prevent disruption of GET requests if a single ' character is contained in a string sent to your server. I would replace ' with %27 in both JavaScript and PHP just in case someone tries to manually send some data to your PHP function.

To make it prettier to your end user, just run an inverse replace function for all data you get back from your server and replace all %27 substrings with '.

Happy injection avoiding!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mike
  • 1
0

Here is how I did it. Silly, but simple.

$singlequote = "'";
$picturefile = getProductPicture($id);

echo showPicture('.$singlequote.$picturefile.$singlequote.');

I was working on outputting HTML that called JavaScript code to show a picture...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131