Seguramente todos ustedes ya estén familiarizados con el termino ”Inyección SQL”, en caso de que no sea así, les comento que así nos referimos al método de infiltración que aprovecha una vulnerabilidad informática muy común en aplicaciones web.
La idea general consiste en inyectar código SQL mediante campos <input> por ejemplo. Ahora, la vulnerabilidad es tal solo si el desarrollador no ah tomado los cuidados suficientes. Aunque no lo crean esto es bastante común.
Para evitar esto basta con “revisar” lo que llega de nuestros formularios, o campos cualquiera sean y validarlos antes de enviarlos a nuestro motor SQL.
En el caso de que estemos utilizando MySql, PHP nos da una mano otorgando el tan utilizado mysql_real_escape_string:
<?php
:$query = sprintf("SELECT * FROM libros WHERE autor='%s'",
addcslashes(mysql_real_escape_string($autor_nombre),'%_'));
mysql_query($query);
?>
Hasta aquí todo iría perfecto para MySQL, pero que sucede cuando estamos utilizando otro motor de base de datos, como ser por ejemplo MS SQL Server. Sencillamente esto no funcionara. Para solucionar esto les traigo el siguiente script:
EvitarInyeccion.php
<?php
if (!function_exists("GetSQLValueString";)) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "";)
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
$theValue = function_exists("mysql_real_escape_string";) ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "";) ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "";) ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "";) ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "";) ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "";) ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
?>
Como se utiliza ? Pues de esta manera:
Supongamos que recibimos mediante un formulario la variable $_POST["nuevoNombre"] y $_POST["edad"]
<?php
include("EvitarInyeccion.php";);
//COMO VERÁN ES NECESARIO DECLARAR EL TIPO DE VARIABLE
$nuevoNombre = GetSQLValueString($_POST["nuevoNombre"], "text";);
$edad = GetSQLValueString($_POST["edad"], "int";);
//GUARDO LA INFORMACION
mssql_query("INSERT INTO datosUsuario (nombre, edad) VALUES (".$nuevoNombre.",".$edad.";)";);
?>
Como verán es bastante sencillo y practico en el caso de que no trabajemos con MySQL, espero que les sirva.