Re: How do I display apostrophe in PHP generated form?

[email protected] (AllenJB)
Newsgroups php.general
Message-ID <[email protected]>
Tip of the day: addslashes() is almost always the wrong function to use 
for escaping output.

You need to escape output for the specific format you're outputting to, 
so in this case html.

In native PHP this can be done using htmlentities().

If you are using single quotes for HTML attributes, if you're not using 
PHP 8.1+ you'll want to explicitly specify the ENT_QUOTES flag.

For further information and examples see the manual: 
https://www.php.net/htmlentities

Many frameworks and templating libraries will provide their own version, 
or you can write your own custom function, that has a nice short name 
and allows you to change the defaults to htmlentities() everywhere you 
use it in one go.

On 28/11/2021 21:35, John wrote:
> I have an application where the user enters a name which is
> subsequently passed to another PHP script for validation using JSON.
> If the user's name is, eg O'Toole, then the initial PHP script accepts
> it correctly, the JSON format passes it correctly and if I just do a
> display of the received JSON block it is correct, but when I put it
> into the <input> element of a form for validation everything to the
> right of the ' gets dropped.
>
> I have tried addslashes() and that results in:  'O'Toole' --> 'O\'
>
> The specific lines of code:
>
> -------
>
> echo $addrdec['address']['city'];  <-- result of associative array
> recovered correctly from JSON coding
>
> results in "St John's"
>
> -------
>
> echo "<input type=text name=rcity id=rcity length=32 size=20 value='"
> . addslashes($addrdec['address']['city']) . "'></input> &emsp;";
>
> results in display "St John\"
>
> Looking at the page source that resulted from this the value part of
> the element (Firefox won't let me copy it directly):
>
> .... size="20" value="St John\" s'="">
>
>
> -------
>
> and if I don't use addslashes the value becomes 'St John', truncating
> the 's' following the apostrophe.  Frankly, I would have expected a
> syntax error if the ' were being used to close the literal but that
> doesn't happen.
>
> Looking at the page source that resulted from this the value part of
> the element (Firefox won't let me copy it directly):
>
> .... size="20" value="St John\" s'="">
>
> How can I resolve this?
>
> Thanks in advance.
>
> John
> ============
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.