Slashes appear in displayed form text despite using stripslashes

287 views Asked by At

I have a comment box form up and running, and I just noticed that when I use ' it creates a \ in front of it. For example, if I write "how's" it shows up as "how\'s" both in the database it's posting to and when it displays on the page. I'm using the stripslashes function when I display the "body" text, which I thought was supposed to get rid of slashes.

My server is running php version 5.3.6, if that helps.

I'm using this piece of code to post the text from the body of the comment box into my database:

$body = mysql_prep($_POST['body']);

The function it is using is this:

function mysql_prep($string) {
    global $connection;

    $escaped_string = mysqli_real_escape_string($connection, $string);
    return $escaped_string;
}

Side note: you don't need to answer this, but that's the function I'm using to make the text users enter safe from hackers, baddies, and all that. Am I doing that alright or am I am leaving myself open to issues? (besides this slash problem that might be because of this function)

This is the code I'm using to display the text:

<div id="comments">
    <?php while($comment_text = mysqli_fetch_assoc($display_comments)) { ?>
    <div class="comment" style="margin-bottom: 2em;">
        <div class="author">
            <b><?php echo htmlentities($comment_text["author"]); ?>:</b>
        </div>
        <div class="meta-info" style="font-size: 0.8em;">
            <?php echo datetime_to_text($comment_text["created"]); ?>
        </div>
        <div class="body">
            <?php echo stripslashes($comment_text["body"], '<strong><em><p>'); ?>
        </div>
    </div>
    <?php } ?>  
    <?php if(empty($display_comments)) { echo "No Comments."; } ?>
</div>

Any help or advice is super appreciated, thanks!!

1

There are 1 answers

0
Yang On BEST ANSWER

Your problem is that, you have Magic Quotes turned on. You can recursively strip all slashes using this approach:

File magic_quotes_filter.php

<?php

if (function_exists('set_magic_quotes_runtime') && get_magic_quotes_gpc()) {

    function stripslashes_deep($value) {
        $value = is_array($value) ?
                    array_map('stripslashes_deep', $value) :
                    stripslashes($value);

        return $value;
    }

    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
    $_REQUEST = array_map('stripslashes_deep', $_REQUEST);  
}

Then yon can simply include('path/to/magic_quotes_filter.php') where you deal with request HTTP variables.

In your case, just include it at the top of your script.