2015-09-28 56 views
2

我只是把我的長代碼縮減到很小,所以它很容易理解。我正在構建基於PHP的網站。我正在使用MySQLi,因爲我知道一些MySQL。而對於我來說PDO很難在很短的時間內學習。使用MySQLi連接數據庫與php的安全方式

我創建三個文件

- db.con.php 
- index.php 
- logout.php 

我會後我的所有三個文件,我只是想知道,如果它的safe或有任何Vulnerability

並感謝所有誰看到我的問題,我和欣賞答案很多。

db.con.php

<?php 
//db.con.php 
class DB { 
    protected $db_name = 'demo'; 
    protected $db_user = 'root'; 
    protected $db_pass = ''; 
    protected $db_host = 'localhost'; 

    public function connect() { 
     $DBerror = 'Database Error'; 
     $connection = ($GLOBALS["___mysqli_ston"] = mysqli_connect($this->db_host, $this->db_user, $this->db_pass)) or die($DBerror); 
     ((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE $this->db_name")) or die($DBerror); 
     return true; 
    } 
} 

$db = new DB(); 
$db->connect(); 

//start session 
session_start(); 
?> 

的index.php

<?php 
require_once 'db.con.php'; 
$userID = $_GET['userID']; 
$userID = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $userID); 

$CheckQuery = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM users WHERE id='$userID'"); 

$VerifyID = mysqli_num_rows($CheckQuery); 
if ($VerifyID !== 1){ 
    header("Location: logout.php"); 
} 

while ($row = mysqli_fetch_assoc($CheckQuery)) { 
    $id = $row['id']; 
    $name = $row['name']; 
} 

echo "My id is $id and my name is $name"; 

?> 

而在去年logout.php

<?php 
//logout.php 
session_start(); 

session_destroy(); 
echo "Logout successful"; 
?> 
+0

您正在使用MySQLi,這意味着您可以使用預準備語句。沒有更多的'mysqli_real_escape_string'!看到這裏:http://bobby-tables.com/php.html –

+0

你的'$連接'似乎對我來說太長:/ –

+0

P.S.您可以將'$ this-> db_name'作爲第四個參數傳遞給'mysqli_connect'。另外,如果你只是將連接保存到'$ GLOBALS [「___ mysqli_ston」]'中,那麼'$ connection'的意義何在? –

回答

4
  1. 讓它PDO不單單mysqli的
  2. 離開DB類一會兒
  3. 瞭解準備好的發言

db.con.php

<?php 
$dsn = "mysql:host=localhost;dbname=demo;charset=utf8"; 
$opt = array(
    PDO::ATTR_ERRMODE   => PDO::ERRMODE_EXCEPTION, 
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC 
); 
$pdo = new PDO($dsn, 'root', '', $opt); 

session_start(); 

的index.php

<?php 
require_once 'db.con.php'; 

$stmt = $pdo->prepare("SELECT 1 FROM users WHERE id=?"); 
$stmt->execute(array($_GET['userID'])); 
$row = $stmt->fetch(); 
if(!$row) { 
    header("Location: logout.php"); 
    exit; 
} 
$id = $row['id']; 
$name = $row['name']; 
echo "My id is $id and my name is $name"; 

看起來沒有自封包裝效果更好

相關問題