Search code examples
phphtmlformsapostrophe

HTML forms, php and apostrophes


Doing a uni assignment with HTML, XML and php 5.3 (no SQL). Building a review website. I have a textarea in which the user can place their comments. If the user enters an apostrophe, eg World's Best Uni!, when I echo $_REQUEST['reviewtext'] I get World\'s Best Uni!

To massage the data for saving in the XML, I have the following code:

$cleantext1 = htmlspecialchars($_REQUEST['reviewtext']);
substr_replace($cleantext1,"\'","'");
$cleantext2 = strip_tags($cleantext1);
$cleantext3 = utf8_encode($cleantext2);

I have echo's at each step an the quote remains World\'s Best Uni! at each step. I expected the one of the first two lines to replace the escaped apostrophe with an html code but it doesn't seem to work.

Interestingly, this problem doesn't happen on my local XAMPP server; only on my hosted website.

Any suggestions? Thanks, Sean


Solution

  • What you are experiencing is PHP's Magic Quotes feature which is automatically escaping input from GET, POST, COOKIE. It is not wise to rely on this feature, and is deprecated as of PHP 5.3, and tends to default to off on most configurations (but not in your Uni's config).

    You can use get_magic_quotes_gpc() to determine if this is turned on, and if so, unescape the data.

    if (get_magic_quotes_gpc()) {
        $val = stripslashes($_POST['val']);
    } else {
        $val = $_POST['val'];
    }
    

    The magic quotes reference goes into more detail on the history, usage, and how to deal with magic quotes.

    Also, just an aside, when you output data, always make sure you escape it (e.g. htmlspecialchars() and when you process input from any untrusted source, make sure to filter it (e.g. addslashes(), mysql_real_escape_string()).