How do I not allow "<" and ">" in my Insert

Asked

Viewed 115 times

0

Well, I have an INSERT, and I would like to make sure that if someone typed in the text something with "<" or ">" that gave error when sending.

Code:

    $autor_id   = $_POST ["autor_id"];  
    $texto  = $_POST ["texto"];
    $query = "INSERT INTO `videos` ( `autor_id` , `texto`, `id` ) 
    VALUES ('$autor_id', '$texto', '')";

    mysql_query($query,$conexao);
  • Could you help me with her?

  • If any answer helped you or solved your problem, take a vote and mark it as the correct answer, otherwise give more details about what you tried and the results you got. Always vote and choose the right answers is good practice and helps other users.

4 answers

1

Instead of avoiding the < and > you could convert them at the time of reading (remember in INSERT it is better to keep the original as it was written), then at the time you use SELECT the < and > will be converted to &lt; and &gt;, thus avoiding injecting HTML into the page, but being able to keep the text as close as the author wrote.

Another thing you should prevent not only the "injection" of HTML, but also the "injection" of mysql (or syntax failures), use mysql_real_escape

$autor_id   = mysql_real_escape($_POST["autor_id"]);
$texto  = mysql_real_escape($_POST["texto"]);
$query = "INSERT INTO `videos` ( `autor_id` , `texto`, `id` ) VALUES ('$autor_id', '$texto', '')";

mysql_query($query,$conexao);

In reading use htmlspecialchars, example:

$query = 'SELECT autor_id, id, texto FROM `videos` LIMIT 30';
$consulta = mysql_query($query, $conexao);

while ($linha = mysql_fetch_assoc($consulta)) {
     echo 'texto: ', htmlspecialchars($linha['texto']), '<br>';
}

Old Mysql Api for PHP vs PDO and Mysqli

As has been said a few times in Sopt:

The php API mysql_ will be discontinued (Does not mean mysql will be discontinued, only the PHP API) as it has been replaced by mysqli_*, then it is strongly recommended that you update your codes to use or mysqli or pdo

Advantages of mysqli

  • Object Oriented Interface (Object-oriented interface)
  • Support for Prepared Statements
  • Support for Multiple Statements
  • Support for transactions (Transactions)
  • Improvement in debugging capacity
  • Support for embedded server

Advantages of PDO

As was said by @Kazzkiq:

  • Perks:

    • Works with 12 different database drivers (4D, MS SQL Server, Firebird/Interbase, Mysql, Oracle, ODBC/DB2, Postgresql, Sqlite, Informix, IBM, CUBRID);
    • Object Oriented API;
    • Has named parameters;
    • It has customer side Prepared statements (see disadvantages below)
  • Disadvantages:

    • Not as fast as MySQLi;
    • By default, it simulates Prepared statements (you can turn on the native version by setting up its connection to the database, but in case the native version doesn’t work for some reason, it resets the Prepared statements without firing errors or warnings. More details here)

Why update your codes

Like I said in this reply, it is necessary to note that the functions mysql_ no longer receive updates such as fixes and improvements and this is the vital point for you no longer to use the mysql_, because in the future it will soon cease to exist for the new versions of PHP.

In other words, if you continue to function mysql_ (without the i), two situations can happen with your projects:

  • There may be gaps in API security mysql_ or bugs.
  • When the API mysql_ if disabled, your scripts will stop working, which will cause you a lot of headache as you will have to redo several codes.

How to use mysqli with your code

The insertion can be like this:

$autor_id   = mysqli_real_escape_string($_POST["autor_id"]);
$texto  = mysqli_real_escape_string($_POST["texto"]);
$query = "INSERT INTO `videos` ( `autor_id` , `texto`, `id` ) VALUES ('$autor_id', '$texto', '')";

mysqli_query($query,$conexao);

In reading use htmlspecialchars, example:

$query = 'SELECT autor_id, id, texto FROM `videos` LIMIT 30';
$consulta = mysqli_query($query, $conexao);

while ($linha = mysqli_fetch_assoc($consulta)) {
     echo 'texto: ', htmlspecialchars($linha['texto']), '<br>';
}

However you can use the Prepared statements, so you won’t need to use mysqli_real_escape_string, example of data entry:

    <?php
    $mysqli = new mysqli("localhost", "my_user", "my_password", "world");

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit;
    }

    $autor_id = $_POST["autor_id"];
    $texto    = $_POST["texto"];

    if ($stmt = $mysqli->prepare("INSERT INTO `videos` ( `autor_id` , `texto`, `id` ) VALUES (?, ?, '')")) {

        $stmt->bind_param('i', $autor_id);
        $stmt->bind_param('s', $texto);

        $stmt->execute();

        while ($linha = $result->fetch_assoc()) {
            echo 'texto: ', htmlspecialchars($linha['texto']), '<br>';
        }
        $stmt->close();
    }

    $mysqli->close();

Documentation:

0

Try to use this:

if (strpos($_POST["texto"],'>') !== false || strpos($_POST["texto"],'<') !== false) {

    echo "Foi detetato > ou < no post!";
    die();
}else{
     // Executa sql aqui.
}

0


I prefer to use regular expressions for this type of check.

Example:

$texto = "Este <é> <um teste >>>para remover<><><><><> caracteres <>";
$resultado = preg_replace("/[<>]/", "", $texto);
echo $resultado;
//Este é um teste para remover caracteres

0

I recommend checking both in PHP, as it has already been answered, and in javascript.

In javascript because the form is not sent, it does not use network, internet and resources of your server for nothing, only the visitor’s browser. The visitor also does not lose the data and you do not need any effort to put the renewed data in the form. In PHP for the wise guys who go through the javascript check, which is only there to help them

To do javascript you can use the form onsubmit property:

...
<script type="text/javascript">
function checaTexto() {
  var strtexto;
  strtexto = document.getElementById("texto").value;  
  if ((strtexto.search("<") != -1) || (strtexto.search(">") != -1)) {
    alert("O texto não pode conter os caracteres '<' e '>'.");
    return false;
  }
}
</script>
...
<form id="formid" onsubmit="return checaTexto()" action="pagina.php">
<textarea id="texto" name="texto">
...

There are several other ways to do, use jQuery to assign the event, variable this for form reference, etc. The example is just one of the ways.

In PHP, as indicated by Hardcoder I think would be appropriate, since you asked for an "error" when sending such characters.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.