簡體   English   中英

如何更好地保護我的數據庫連接

[英]How can I better secure my database connection

有人告訴我,這段代碼是舊的連接方式,容易受到sql注入的影響。 如何確保它的安全性?

這是我用來檢查數據庫的用戶並在沒有帳戶的情況下添加新用戶的代碼。 我嘗試了mysqli,但是我認為我做錯了,所以我現在必須回到現在,直到我知道如何使其安全為止。

<?php
// Connect to the database(host, username, password)
$con = mysql_connect('localhost','user1','pass1');
if (!$con)
{
    echo "Failed to make connection.";
    exit;
}
// Select the database. Enter the name of your database (not the same as the table name)
$db = mysql_select_db('db1');
if (!$db)
{
    echo "Failed to select db.";
    exit;
}
// $_POST['username'] and $_POST['password'] are the param names we sent in our click event in login.js
$username = $_POST['username'];
$password = $_POST['password'];
// Select eveything from the users table where username field == the username we posted and password field == the password we posted
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . $password . "'";
$query = mysql_query($sql);
// If we find a match, create an array of data, json_encode it and echo it out
if (mysql_num_rows($query) > 0)
{
    $row = mysql_fetch_array($query);
    $response = array(
        'logged' => true,
        'name' => $row['name'],
        'email' => $row['email']
    );
    echo json_encode($response);
}
else
{
    // Else the username and/or password was invalid! Create an array, json_encode it and echo it out
    $response = array(
        'logged' => false,
        'message' => 'Invalid Username and/or Password'
    );
    echo json_encode($response);
}
?>

來自用戶的任何數據都應通過mysql_real_escape_string()傳遞。 有關使用該功能的更多信息,請參見下面的URL。 這很重要。

http://php.net/manual/zh/function.mysql-real-escape-string.php

這是有關使用PHP進行SQL注入的更多信息:

http://php.net/manual/zh/security.database.sql-injection.php

MySQLi信息(除mysql_real_escape_string之外的另一種技術):

http://php.net/manual/zh/mysqli.quickstart.prepared-statements.php

編輯:好的,我承認,我有點老派。 MySQLi無疑是必經之路。 我對PHP3和PHP4開發更加熟悉。 如果可以,請使用最后一個鏈接重新實現數據訪問代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM