Search code examples
phphtml-escape-characters

php/javascript Best way to escape quotes in querystring


I use ajax with php to output hyperlinks enabling user to email some text. The link points to a mail script and the querystring contains the text to mail. By clicking on the link, the user mails the text. However, if text (also user created) contains a quote mark, this quote mark appears in the querystring and breaks the code. Specifically, the browser thinks the querystring ends when it encounters the quote. The text after the quote spills out onto the page. I could enclose the hyperlink in an apostrophe instead of a quote, but then I'd have the same problem if the user included an apostrophe in the text.

I have tried to escape these special characters using json_encode but that did not work. I know there is addslashes or maybe I could hack somethin with str_replace, but would like to do this the right way.

Thanks for any suggestions on the right way to do this.

php

go to dbase

$text = $row['text'];

echo '<a href="sendmail.php?text='.$text.'">email text</a>';

/*
say for sake of argument text is 'the dimensions of the painting are 24" x 36"'

then above link is

echo '<a href="sendmail.php?text=the dimensions of the painting are 24" x 36"">email text</a>';
 which breaks code
*/

Solution

  • urlencode should be used, since you're encoding the text to put it in a URL.