Forum Moderators: coopster

Message Too Old, No Replies

Odd apostrophe behavior

         

SeanF

9:19 am on Jul 28, 2022 (gmt 0)

5+ Year Member Top Contributors Of The Month



I am sure this is a very basic problem that I have overlooked for years but it hasn't ever been a problem.

I have a very simple php script with an HTML form which edits company information (stored in a MySQL database). The problem is where a company name includes an apostrophe like "Bob's Store"

The string is saved to the database using add slashes:
$company_name = addslashes(strip_tags($_POST['company_name']));

On the edit page, the string is retrieved using stripslashes:
$company_name = stripslashes($row_data['company_name']);

and echoed to the screen as part of the page title. The string looks fine.

The string is then included in the edit form as such:
<input type='text' name='company_name' size=55 maxlength=55 value='$company_name'>

The problem is that the text which appears in the input field is truncated after the apostrophe: "Bob".
If I remove the apostrophes around $company_name:
<input type='text' name='company_name' size=55 maxlength=55 value=$company_name>

the text is truncated after the space: "Bob's"

This script/form has been used for almost 20 years, there are more than 25K companies in the table and more than a thousand have apostrophes in their names and I've never had this problem.

What am I missing?

brotherhood of LAN

9:54 am on Jul 28, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Don't use addslashes to sanitise input, use mysqli_escape_string or whichever variant/version of it in PHP you use. This will store the value as it seen on the form.

Use htmlentities to display it safely back on an HTML page. You won't need to stripslashes because the string was already properly escaped for insertion to the DB.

You're seeing it truncated because you're using apostrophes for the HTML attributes, the quote in Bob's name is acting as a closing apostrophe for the element. Use double quotes for value=""

If someone were to submit their name with a " in it and you accepted it, htmlentities would convert it to &quot;, and would still display fine as a form value.

robzilla

2:06 pm on Jul 28, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



As noted in the comments on the stripslashes() [php.net] function page, "keep in mind that single quote is not the only special character that can break your sql query."