Skip to main content
 首页 » 编程设计

php之在 SQLite3 中避免 SQL 注入(inject)

2025年12月25日44JustinYoung

我正在尝试找到一种避免 SQL 注入(inject)的简单好方法,但到目前为止我只能提出两个想法:

  • Base64 对用户输入进行编码(我真的不想这样做)
  • 使用正则表达式删除不需要的字符。 (目前正在使用这个,不确定它是否 100% 安全)

这是我当前的代码:

    <?php 
        $hash = $_GET['file']; 
 
        if (isset($hash)) 
        { 
            $db = new SQLite3("Files.db"); 
 
            if ($db != null) 
            { 
                $hash = preg_replace('/[^A-Za-z0-9 _.\-+=]/', '_', $hash); 
 
                if ($response = $db->query("SELECT [FILE] FROM '$hash'")) 
                { 
                    echo $response->fetchArray()[0]; // File name is returned if successful. 
                } 
            } 
        } 
    ?> 

我的问题是我这样做的方式是否正确,或者是否有更好的方式来做到这一点?

请您参考如下方法:

让您的数据库图书馆为您做这件事。 PHP Sqlite3 库支持 prepared statements :

$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id'); 
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);