I'm making a site with PHP-MySQL that allows users to input text into a database, and displays it on various pages.

I know of the htmlspecialchars function, but I am not completely sure about how to use it. Most of my pages query the database for about 10 fields of information from the DB, and as far as I can tell, I will need to put htmlspecialchars before each of those queries. Is there an easier way to block HTML on a page? Is it possible to loop a htmlspecialchars so that it applies to several instances of code on one page?

I've tried:

$query = @mysql_query("SELECT * FROM table");
$row1 = mysql_fetch_array($query);
$row2 = htmlspecialchars($row1);

echo "$row2[fieldname]";

but get a "htmlspecialchars() expects parameter 1 to be string, array given in path\to\site\htdocs\index.php" error message.

    The easiest way to block html is to use htmlentities before you store each of the things that your users will post. For example:

    user has a text box. puts in a string and submits form.
    receiving scripts takes passed string and runs it through htmlentities. then store it in the database. On pulling info back out of the database you can then just display it as it's stored with no worry of html code.

      Originally posted by ereptur
      The easiest way to block html is to use htmlentities before you store each of the things that your users will post. For example:

      user has a text box. puts in a string and submits form.
      receiving scripts takes passed string and runs it through htmlentities. then store it in the database. On pulling info back out of the database you can then just display it as it's stored with no worry of html code.

      I have 10 fields that are submitted into an "INSERT INTO tablename SET field1='$entry1'" query. Do you know of any loop I can use so that I won't have to code $secureentry1 = htmlentities('$entry1'); for every field?

        try this

        
        foreach($_POST as $key){
        if($value != "submit"){//the name of the submit button
          $sql .= $key."='".htmlentities($value)."',";
          }else{
          exit;
          }
        }
        
        

        Then just use

        It may not work as i didnt test it, if so just play around with it.

          You could do this

          foreach( $_POST as $key => $value )
              $$key = htmletities( $value );
          

          This will obviously do it to every $_POST value which may not be suitable for some of the entries.

          HalfaBee ( Started this reply 15 mins ago and got interupted 🙂 )

            Write a Reply...