开发者

How to improve PHP code against SQL injection and other threats

开发者 https://www.devze.com 2023-04-09 08:48 出处:网络
How can I modify this code to improve protection against sql injection and other threats? It is a MS SQL database.

How can I modify this code to improve protection against sql injection and other threats? It is a MS SQL database.

<?php include_once("db.php"); ?>

<?php
$id = $_REQUEST['id'];
settype($id, 'string');

$tsql = "SELECT Table1.Fund FROM Table1 WHERE Table1.Fund='%s'";
$tsqlnew=sprintf($tsql, $id);

$stmt = sqlsrv_query( $conn, $tsqlnew);
if( $stmt === false)
{
echo "Error in query preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}

$chd = '';

while( $data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))  {
$chd .= '[\''.$data['Fund'] .'\'],';
}
$chd = substr($chd,0,-1);

?>

I'm also wondering if my db connection can be improved. Thanks for your help!

<?php

$myServer = "server";
$myUser = "userPlaceHolder";
$myPass = "passwordPlaceHolder";
$myDB = "SQL";

$conn = sqlsrv_connect($m开发者_如何学PythonyServer, array('UID'=>$myUser, 'PWD'=>$myPass, 'Database'=>$myDB));

if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
?>


You code does exactly NOTHING to prevent injection attacks. Merely forcing variable to have a string-data type is exactly as much protection as a piece of toilet paper provides against a tsunami.

To prevent injection attacks, you must escape all data that you insert into a query string, whether it's user-provided or something you yourself have created/inserted.

Best option is to use prepared statements, which relieves you of the responsibility of escaping data.

Even if the data being inserted isn't "malicious", any SQL metacharacters (quotes in particular) can still destroy the query and cause syntax errors.

0

精彩评论

暂无评论...
验证码 换一张
取 消