Alexander
Alexander

Reputation: 131

Escape quotes in a variable with PHP

I use this code to genefate html

echo "<input type='button' onclick=\"myFunc('$param');\" />";

Everything would be OK unless $param contains ' or " character. How should it be implemented to handle these situations?

ps. mysql_real_escape_string($param) won't work correctly, when a user entered ".

Upvotes: 9

Views: 15070

Answers (7)

PM1625637
PM1625637

Reputation: 108

This works for me...

echo '<a href="#" onclick="showTable(&#039;'.$table.'&#039;)">'.$table.'</a>';

It's not necessary to use backslaches for escaping when using single quote for echo. Single quote have my vote to work with both php and javascript + html tag.

Upvotes: 0

Shakti Singh
Shakti Singh

Reputation: 86446

Pass variable from htmlspecialchars($pram,ENT_QUOTES)

Upvotes: 2

NoxArt
NoxArt

Reputation: 361

Whenever thinking about escaping, you always need to ask
"In which context do I want to escape?"
Because escaping is essentialy making sure the input is not interpreted in the special meaning of the target, but literaly

Do not use addslashes, since it's contextless

If you are inserting the string into HTML, use

htmlspecialchars($argument, ENT_QUOTES)

as mentioned.

The onclick content part is technicaly JavaScript, so it might be appropriate to escape the content with json_encode (it's side-effect is JavaScript-specific escaping). Similarly should you have style attribute, you'd want to escape the content with

addcslashes($s, "\x00..\x2C./:;<=>?@[\\]^`{|}~")

(source: http://translate.google.com/translate?u=http%3A%2F%2Fphpfashion.com%2Fescapovani-definitivni-prirucka&ie=UTF8&sl=cs&tl=en)

Summary
Use

$param = htmlspecialchars(json_encode($param), ENT_QUOTES)

and then you can safely include it into the HTML string

Upvotes: 2

xkeshav
xkeshav

Reputation: 54060

first do

// only for the GUY who didn't read the complete answer :(
$param=addslashes($param); 

then write code in simple HTML

<input type='button' onclick="myFunc(<?php echo $param?>);" />

Note: mysql_real_escape_string works when we handle with mysqltry with addslashes

Upvotes: 1

jbasko
jbasko

Reputation: 7330

If you are relying on user input, use htmlentities($param, ENT_QUOTES);

See http://uk.php.net/manual/en/function.htmlentities.php

Upvotes: 7

Nick
Nick

Reputation: 6965

There are a couple of functions that could be used:

<?php
$string = 'string test"';

echo htmlentities($string) . "\n";
echo addslashes($string) . "\n";

They produce the following:

string test&quot;
string test\"

Upvotes: 10

Adam Purdie
Adam Purdie

Reputation: 502

As Damien said; use addslashes :)

$param=addslashes($param);
echo "<input type='button' onclick=\"myFunc('$param');\" />";

Upvotes: 5

Related Questions