简体   繁体   中英

htmlspecialchars in PHP

Can someone help me adding the htmlspecialchars to prevent XSS in this code:

<?PHP
    if(isset($_POST['update'])) { 
        $ts=$_POST['ts'];
        $user=$_POST['user'];

        mysql_query("UPDATE users SET block_newfriends='". mysql_real_escape_string($ts). "'  WHERE username='" .mysql_real_escape_string($user) . "'");
        echo '<div class="rounded-container">';
        echo '<div class="rounded-green rounded-done">';
        echo '<b>reload</b><br>';
        echo '</div>';
        echo '</div>';
    }
?>

I don't know where to put them, it should be in the POST function right?

Replace the $ts and $user lines with:

$ts=htmlspecialchars($_POST['ts']);
$user=htmlspecialchars($_POST['user']);

Then leave the query alone, it will then use mysql_real_escape_string() on the htmlspecialchars stripped value.

You need to make it safe using different functions depending on what you want to do:

When you output to HTML, make it "html-safe" by wrapping in htmlspecialchars .

echo 'Writing to browser ' . htmlspecialchars($_POST['t']);

When you output to SQL, make it "sql-safe" by escaping it for sql (see note below).

$sql = 'UPDATE table SET field="' . mysql_escape_string($_POST['t']);

When you output to a URL, make it "url-safe" by escaping it for urls.

$link = 'http:/example.com?value=' . urlencode($_POST['t'])

Similar rules apply for JSON encoding, outputting to XML etc.


Note on mySQL: you are correct to escape it, but you are using functions that no longer exist in PHP (you are therefore using an old version of PHP). Check mysqli or pdo in the manual and use those functions instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM