當前位置:首頁 » 編程語言 » php代碼注入

php代碼注入

發布時間: 2022-06-22 16:02:22

1. php如何防止sql注入

PHP防止sql注入是一個比較低級的問題了,這個問題其實在我大一上學期做第一個個人博客的時候就已經關注過了,不過簡單的說一下關於PHP防注入的方式吧。


對於現在的防注入技術其實已經成熟了,對於一個站點該關心的不是防注入了,而是大規模高並發如何處理的問題,或者關於各種其他漏洞,比如現在世界上仍然有百分之80使用redis的站點存在redis漏洞,通過redis漏洞可以直接拿到機器的訪問許可權,一般來說都是直接給你種一個挖礦機器人來。

2. PHP中什麼是依賴注入

依賴注入可能是我所知道的最簡單設計模式之一,很多情況下可能你無意識中已經使用了依賴注入。不過它也是最難解釋的一個。我認為有一部分原因是由於大多數介紹依賴注入的例子缺乏實際意義,讓人難理解。因為PHP主要用於Web開發,那就先來看一個簡單的web開發實例。
HTTP本身是一個無狀態的連接協議,為了支持客戶在發起WEB請求時應用程序能存儲用戶信息,我們就需要通過一種技術來實現存儲狀態交互。理所當然最簡單的是使用cookie,更好的方式是PHP內置的Session機制。
$_SESSION['language'] = 'fr';
上面代碼將用戶語言存儲在了名為language的Session變數中,因此在該用戶隨後的請求中,可以通過全局數組$_SESSION來獲取language:
$user_language = $_SESSION['language'];
依賴注入主要用於面向對像開發,現在讓我們假設我們有一個SessionStorage類,該類封裝了PHP Session機制:
class SessionStorage
{
function __construct($cookieName = 'PHP_SESS_ID')
{
session_name($cookieName);
session_start();
}
function set($key, $value)
{
$_SESSION[$key] = $value;
}
function get($key)
{
return $_SESSION[$key];
}
// ...
}
同時還有一個User類提供了更高級的封裝:
class User
{
protected $storage;
function __construct()
{
$this->storage = new SessionStorage();
}
function setLanguage($language)
{
$this->storage->set('language', $language);
}
function getLanguage()
{
return $this->storage->get('language');
}
// ...
}
代碼很簡單,同樣使用User類也很簡單:
$user = new User();
$user->setLanguage('fr');
$user_language = $user->getLanguage();
一切都很美好,除非你的程序需要更好的擴展性。假設現在你想要更改保存session_id的COOKIE鍵值,以下有一些可供選擇的方法:
User類中創建SessionStorage實例時,在SessionStorage構造方法中使用字元串』SESSION_ID』硬編碼:
class User
{
function __construct()
{
$this->storage = new SessionStorage('SESSION_ID');
}
// ...
}
在User類外部設置一個常量(名為STORAGE_SESSION_NAME)
class User
{
function __construct()
{
$this->storage = new SessionStorage(STORAGE_SESSION_NAME);
}
// ...
}
define('STORAGE_SESSION_NAME', 'SESSION_ID');
通過User類構造函數中的參數傳遞Session name
class User
{
function __construct($sessionName)
{
$this->storage = new SessionStorage($sessionName);
}
// ...
}
$user = new User('SESSION_ID');
還是通過User類構造函數中的參數傳遞Session name,不過這次參數採用數組的方式
class User
{
function __construct($storageOptions)
{
$this->storage = new SessionStorage($storageOptions['session_name']);
}
// ...
}
$user = new User(array('session_name' => 'SESSION_ID'));
上面的方式都很糟糕。
在user類中硬編碼設置session name的做法沒有真正解決問題,如果以後你還需要更改保存session_id的COOKIE鍵值,你不得不再一次修改user類(User類不應該關心COOKIE鍵值)。
使用常量的方式同樣很糟,造成User類依賴於一個常量設置。
通過User類構造函數的參數或數組來傳遞session name相對來說好一些,不過也不完美,這樣做干擾了User類構造函數的參數,因為如何存儲Session並不是User類需要關心的,User類不應該和它們扯上關聯。
另外,還有一個問題不太好解決:我們如何改變SessionStorage類。這種應用場景很多,比如你要用一個Session模擬類來做測試,或者你要將Session存儲在資料庫或者內存中。目前這種實現方式,在不改變User類的情況下,很難做到這點。
現在,讓我們來使用依賴注入。回憶一下,之前我們是在User類內部創建SessionStorage對像的,現在我們修改一下,讓SessionStorage對像通過User類的構造函數傳遞進去。
class User
{
function __construct($storage)
{
$this->storage = $storage;
}
// ...
這就是依賴注入最經典的案例,沒有之一。現在使用User類有一些小小的改變,首先你需要創建SessionStorage對像。
$storage = new SessionStorage('SESSION_ID');
$user = new User($storage);
現在,配置session存儲對像很簡單了,同樣如果改變session存儲對像也很簡單,所有這一切並不需要去更新User類,降低了業務類之間的耦合。
Pico Container 的網站上是這樣描述依賴注入:
依賴注入是通過類的構造函數、方法、或者直接寫入的方式,將所依賴的組件傳遞給類的方式。
所以依賴注入並不只限於通過構造函數注入。下面來看看幾種注入方式:
構造函數注入
class User
{
function __construct($storage)
{
$this->storage = $storage;
}
// ...
}
setter方法注入
class User
{
function setSessionStorage($storage)
{
$this->storage = $storage;
}
// ...
}
屬性直接注入
class User
{
public $sessionStorage;
}
$user->sessionStorage = $storage;
根據經驗,一般通過構造函數注入的是強依賴關系的組件,setter方式用來注入可選的依賴組件。
現在,大多數流行的PHP框架都採用了依賴注入的模式實現業務組件間的高內聚低耦合。
// symfony: 構造函數注入的例子
$dispatcher = new sfEventDispatcher();
$storage = new sfMySQLSessionStorage(array('database' => 'session', 'db_table' => 'session'));
$user = new sfUser($dispatcher, $storage, array('default_culture' => 'en'));
// Zend Framework: setter方式注入的例子
$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', array(
'auth' => 'login',
'username' => 'foo',
'password' => 'bar',
'ssl' => 'ssl',
'port' => 465,
));
$mailer = new Zend_Mail();
$mailer->setDefaultTransport($transport);

3. 如何防止代碼注入攻擊在PHP

一,HTML防注入。
一般的html注入都是在字元串中加入了html標簽,用下JAVA代碼可以去掉這部分代碼。
代碼如下,自己封裝成方法即可。
String msge = "asdasdasdasd <div id=\"f\">asdfsdf";
System.out.println(msge);
msge = msge.replace("&", "&");
msge = msge.replace("<", "<");
msge = msge.replace(" ", " ");
msge = msge.replace(">", ">");
msge = msge.replace("\"", """);
msge = msge.replace("'", "&qpos;");
System.out.println(msge);
二、防SQL注入
最簡單最容易的是限制用戶輸入。
簡單點的就是不允許用戶輸入單引號 和 --,因為單引號號--在SQL中都是影響執行的。
但SQL注入是多方面的,防止的方法也有很多種。
1、地址欄禁止特殊字元防SQL注入

把特殊字元(如and、or、'、")都禁止提交就可以防止注入了。

2、php過濾html字元串,防止SQL注入
批量過濾post,get敏感數據
$_GET = stripslashes_array($_GET);
$_POST = stripslashes_array($_POST);
數據過濾函數
function stripslashes_array(&$array) {
while(list($key,$var) = each($array)) {
if ($key != 'argc' && $key != 'argv' && (strtoupper($key) != $key || ''.intval($key) == "$key")) {
if (is_string($var)) {
$array[$key] = stripslashes($var);
}
if (is_array($var)) {
$array[$key] = stripslashes_array($var);
}
}
}
return $array;
}
3、替換HTML尾標簽
function lib_replace_end_tag($str)
{
if (empty($str)) return false;
$str = htmlspecialchars($str);
$str = str_replace( '/', "", $str);
$str = str_replace("\\", "", $str);
$str = str_replace(">", "", $str);
$str = str_replace("<", "", $str);
$str = str_replace("<SCRIPT>", "", $str);
$str = str_replace("</SCRIPT>", "", $str);
$str = str_replace("<script>", "", $str);
$str = str_replace("</script>", "", $str);
$str=str_replace("select","select",$str);
$str=str_replace("join","join",$str);
$str=str_replace("union","union",$str);
$str=str_replace("where","where",$str);
$str=str_replace("insert","insert",$str);
$str=str_replace("delete","delete",$str);
$str=str_replace("update","update",$str);
$str=str_replace("like","like",$str);
$str=str_replace("drop","drop",$str);
$str=str_replace("create","create",$str);
$str=str_replace("modify","modify",$str);
$str=str_replace("rename","rename",$str);
$str=str_replace("alter","alter",$str);
$str=str_replace("cas","cast",$str);
$str=str_replace("&","&",$str);
$str=str_replace(">",">",$str);
$str=str_replace("<","<",$str);
$str=str_replace(" ",chr(32),$str);
$str=str_replace(" ",chr(9),$str);
$str=str_replace(" ",chr(9),$str);
$str=str_replace("&",chr(34),$str);
$str=str_replace("'",chr(39),$str);
$str=str_replace("<br />",chr(13),$str);
$str=str_replace("''","'",$str);
$str=str_replace("css","'",$str);
$str=str_replace("CSS","'",$str);
return $str;
}
三、專業的事情交給專業的工具去做。
安裝安全軟體。例如,在伺服器中安裝「伺服器安全狗」,可以設置防注入,防攻擊的設置,只要設置好安全規則,就可以屏蔽大多數攻擊入侵。

4. PHP網站怎麼sql注入有沒有破解防禦的方法

網站的運行安全肯定是每個站長必須考慮的問題,大家知道,大多數黑客攻擊網站都是採用sql注入,這就是我們常說的為什麼最原始的靜態的網站反而是最安全的。 今天我們講講PHP注入的安全規范,防止自己的網站被sql注入。
如今主流的網站開發語言還是php,那我們就從php網站如何防止sql注入開始說起:
Php注入的安全防範通過上面的過程,我們可以了解到php注入的原理和手法,當然我們也同樣可以制定出相應該的防範方法:
首先是對伺服器的安全設置,這里主要是php+mysql的安全設置和linux主機的安全設置。對php+mysql注射的防範,首先將magic_quotes_gpc設置為On,display_errors設置為Off,如果id型,我們利用intval()將其轉換成整數類型,如代碼:
$id=intval($id);
mysql_query=」select *from example where articieid=』$id』」;或者這樣寫:mysql_query(」SELECT * FROM article WHERE articleid=」.intval($id).」")
如果是字元型就用addslashes()過濾一下,然後再過濾」%」和」_」如:
$search=addslashes($search);
$search=str_replace(「_」,」\_」,$search);
$search=str_replace(「%」,」\%」,$search);
當然也可以加php通用防注入代碼:
/*************************
PHP通用防注入安全代碼
說明:
判斷傳遞的變數中是否含有非法字元
如$_POST、$_GET
功能:
防注入
**************************/
//要過濾的非法字元
$ArrFiltrate=array(」『」,」;」,」union」);
//出錯後要跳轉的url,不填則默認前一頁
$StrGoUrl=」";
//是否存在數組中的值
function FunStringExist($StrFiltrate,$ArrFiltrate){
foreach ($ArrFiltrate as $key=>$value){
if (eregi($value,$StrFiltrate)){
return true;
}
}
return false;
}
//合並$_POST 和 $_GET
if(function_exists(array_merge)){
$ArrPostAndGet=array_merge($HTTP_POST_VARS,$HTTP_GET_VARS);
}else{
foreach($HTTP_POST_VARS as $key=>$value){
$ArrPostAndGet[]=$value;
}
foreach($HTTP_GET_VARS as $key=>$value){
$ArrPostAndGet[]=$value;
}
}
//驗證開始
foreach($ArrPostAndGet as $key=>$value){
if (FunStringExist($value,$ArrFiltrate)){
echo 「alert(/」Neeao提示,非法字元/」);」;
if (empty($StrGoUrl)){
echo 「history.go(-1);」;
}else{
echo 「window.location=/」".$StrGoUrl.」/」;」;
}
exit;
}
}
?>
/*************************
保存為checkpostandget.php
然後在每個php文件前加include(「checkpostandget.php「);即可
**************************/
另外將管理員用戶名和密碼都採取md5加密,這樣就能有效地防止了php的注入。
還有伺服器和mysql也要加強一些安全防範。
對於linux伺服器的安全設置:
加密口令,使用「/usr/sbin/authconfig」工具打開密碼的shadow功能,對password進行加密。
禁止訪問重要文件,進入linux命令界面,在提示符下輸入:
#chmod 600 /etc/inetd.conf //改變文件屬性為600
#chattr +I /etc/inetd.conf //保證文件屬主為root
#chattr –I /etc/inetd.conf // 對該文件的改變做限制
禁止任何用戶通過su命令改變為root用戶
在su配置文件即/etc/pam.d/目錄下的開頭添加下面兩行:
Auth sufficient /lib/security/pam_rootok.so debug
Auth required /lib/security/pam_whell.so group=wheel
刪除所有的特殊帳戶
#userdel lp等等 刪除用戶
#groupdel lp等等 刪除組
禁止不使用的suid/sgid程序
#find / -type f \(-perm -04000 - o –perm -02000 \) \-execls –lg {} \;

5. php怎麼實例化有依賴注入的類

PHP依賴注入的理解。分享給大家供大家參考,具體如下:
看Laravel的IoC容器文檔只是介紹實例,但是沒有說原理,之前用MVC框架都沒有在意這個概念,無意中在phalcon的文檔中看到這個詳細的介紹,感覺豁然開朗,復制粘貼過來,主要是好久沒有寫東西了,現在確實很懶變得!
首先,我們假設,我們要開發一個組件命名為SomeComponent。這個組件中現在將要注入一個資料庫連接。
在這個例子中,資料庫連接在component中被創建,這種方法是不切實際的,這樣做的話,我們將不能改變資料庫連接參數及資料庫類型等一些參數。
class SomeComponent {
/**
* The instantiation of the connection is hardcoded inside
* the component so is difficult to replace it externally
* or change its behavior
*/
public function someDbTask()
{
$connection = new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
// ...
}
}
$some = new SomeComponent();
$some->someDbTask();
為了解決上面所說的問題,我們需要在使用前創建一個外部連接,並注入到容器中。就目前而言,這看起來是一個很好的解決方案:
class SomeComponent {
protected $_connection;
/**
* Sets the connection externally
*/
public function setConnection($connection)
{
$this->_connection = $connection;
}
public function someDbTask()
{
$connection = $this->_connection;
// ...
}
}
$some = new SomeComponent();
//Create the connection
$connection = new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
//Inject the connection in the component
$some->setConnection($connection);
$some->someDbTask();
現在我們來考慮一個問題,我們在應用程序中的不同地方使用此組件,將多次創建資料庫連接。使用一種類似全局注冊表的方式,從這獲得一個資料庫連接實例,而不是使用一次就創建一次。
class Registry
{
/**
* Returns the connection
*/
public static function getConnection()
{
return new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
}
}
class SomeComponent
{
protected $_connection;
/**
* Sets the connection externally
*/
public function setConnection($connection){
$this->_connection = $connection;
}
public function someDbTask()
{
$connection = $this->_connection;
// ...
}
}
$some = new SomeComponent();
//Pass the connection defined in the registry
$some->setConnection(Registry::getConnection());
$some->someDbTask();
現在,讓我們來想像一下,我們必須在組件中實現兩個方法,首先需要創建一個新的資料庫連接,第二個總是獲得一個共享連接:
class Registry
{
protected static $_connection;
/**
* Creates a connection
*/
protected static function _createConnection()
{
return new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
}
/**
* Creates a connection only once and returns it
*/
public static function getSharedConnection()
{
if (self::$_connection===null){
$connection = self::_createConnection();
self::$_connection = $connection;
}
return self::$_connection;
}
/**
* Always returns a new connection
*/
public static function getNewConnection()
{
return self::_createConnection();
}
}
class SomeComponent
{
protected $_connection;
/**
* Sets the connection externally
*/
public function setConnection($connection){
$this->_connection = $connection;
}
/**
* This method always needs the shared connection
*/
public function someDbTask()
{
$connection = $this->_connection;
// ...
}
/**
* This method always needs a new connection
*/
public function someOtherDbTask($connection)
{
}
}
$some = new SomeComponent();
//This injects the shared connection
$some->setConnection(Registry::getSharedConnection());
$some->someDbTask();
//Here, we always pass a new connection as parameter
$some->someOtherDbTask(Registry::getConnection());
到此為止,我們已經看到了如何使用依賴注入解決我們的問題。不是在代碼內部創建依賴關系,而是讓其作為一個參數傳遞,這使得我們的程序更容易維護,降低程序代碼的耦合度,實現一種松耦合。但是從長遠來看,這種形式的依賴注入也有一些缺點。
例如,如果組件中有較多的依賴關系,我們需要創建多個setter方法傳遞,或創建構造函數進行傳遞。另外,每次使用組件時,都需要創建依賴組件,使代碼維護不太易,我們編寫的代碼可能像這樣:
//Create the dependencies or retrieve them from the registry
$connection = new Connection();
$session = new Session();
$fileSystem = new FileSystem();
$filter = new Filter();
$selector = new Selector();
//Pass them as constructor parameters
$some = new SomeComponent($connection, $session, $fileSystem, $filter, $selector);
// ... or using setters
$some->setConnection($connection);
$some->setSession($session);
$some->setFileSystem($fileSystem);
$some->setFilter($filter);
$some->setSelector($selector);
我想,我們不得不在應用程序的許多地方創建這個對象。如果你不需要依賴的組件後,我們又要去代碼注入部分移除構造函數中的參數或者是setter方法。為了解決這個問題,我們再次返回去使用一個全局注冊表來創建組件。但是,在創建對象之前,它增加了一個新的抽象層:
class SomeComponent
{
// ...
/**
* Define a factory method to create SomeComponent instances injecting its dependencies
*/
public static function factory()
{
$connection = new Connection();
$session = new Session();
$fileSystem = new FileSystem();
$filter = new Filter();
$selector = new Selector();
return new self($connection, $session, $fileSystem, $filter, $selector);
}
}
這一刻,我們好像回到了問題的開始,我們正在創建組件內部的依賴,我們每次都在修改以及找尋一種解決問題的辦法,但這都不是很好的做法。
一種實用和優雅的來解決這些問題,是使用容器的依賴注入,像我們在前面看到的,容器作為全局注冊表,使用容器的依賴注入做為一種橋梁來解決依賴可以使我們的代碼耦合度更低,很好的降低了組件的復雜性:
class SomeComponent
{
protected $_di;
public function __construct($di)
{
$this->_di = $di;
}
public function someDbTask()
{
// Get the connection service
// Always returns a new connection
$connection = $this->_di->get('db');
}
public function someOtherDbTask()
{
// Get a shared connection service,
// this will return the same connection everytime
$connection = $this->_di->getShared('db');
//This method also requires a input filtering service
$filter = $this->_db->get('filter');
}
}
$di = new Phalcon\DI();
//Register a "db" service in the container
$di->set('db', function(){
return new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
});
//Register a "filter" service in the container
$di->set('filter', function(){
return new Filter();
});
//Register a "session" service in the container
$di->set('session', function(){
return new Session();
});
//Pass the service container as unique parameter
$some = new SomeComponent($di);
$some->someTask();
現在,該組件只有訪問某種service的時候才需要它,如果它不需要,它甚至不初始化,以節約資源。該組件是高度解耦。他們的行為,或者說他們的任何其他方面都不會影響到組件本身。我們的實現辦法
Phalcon\DI 是一個實現了服務的依賴注入功能的組件,它本身也是一個容器。
由於Phalcon高度解耦,Phalcon\DI 是框架用來集成其他組件的必不可少的部分,開發人員也可以使用這個組件依賴注入和管理應用程序中不同類文件的實例。
基本上,這個組件實現了 Inversion of Control 模式。基於此,對象不再以構造函數接收參數或者使用setter的方式來實現注入,而是直接請求服務的依賴注入。這就大大降低了整體程序的復雜性,因為只有一個方法用以獲得所需要的一個組件的依賴關系。
此外,這種模式增強了代碼的可測試性,從而使它不容易出錯。
在容器中注冊服務
框架本身或開發人員都可以注冊服務。當一個組件A要求調用組件B(或它的類的一個實例),可以從容器中請求調用組件B,而不是創建組件B的一個實例。
這種工作方式為我們提供了許多優點:
我們可以更換一個組件,從他們本身或者第三方輕松創建。
在組件發布之前,我們可以充分的控制對象的初始化,並對對象進行各種設置。
我們可以使用統一的方式從組件得到一個結構化的全局實例
服務可以通過以下幾種方式注入到容器:
//Create the Dependency Injector Container
$di = new Phalcon\DI();
//By its class name
$di->set("request", 'Phalcon\Http\Request');
//Using an anonymous function, the instance will lazy loaded
$di->set("request", function(){
return new Phalcon\Http\Request();
});
//Registering directly an instance
$di->set("request", new Phalcon\Http\Request());
//Using an array definition
$di->set("request", array(
"className" => 'Phalcon\Http\Request'
));
在上面的例子中,當向框架請求訪問一個請求數據時,它將首先確定容器中是否存在這個」reqeust」名稱的服務。
容器會反回一個請求數據的實例,開發人員最終得到他們想要的組件。
在上面示例中的每一種方法都有優缺點,具體使用哪一種,由開發過程中的特定場景來決定的。
用一個字元串來設定一個服務非常簡單,但缺少靈活性。設置服務時,使用數組則提供了更多的靈活性,而且可以使用較復雜的代碼。lambda函數是兩者之間一個很好的平衡,但也可能導致更多的維護管理成本。
Phalcon\DI 提供服務的延遲載入。除非開發人員在注入服務的時候直接實例化一個對象,然後存存儲到容器中。在容器中,通過數組,字元串等方式存儲的服務都將被延遲載入,即只有在請求對象的時候才被初始化。
//Register a service "db" with a class name and its parameters
$di->set("db", array(
"className" => "Phalcon\Db\Adapter\Pdo\Mysql",
"parameters" => array(
"parameter" => array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "blog"
)
)
));
//Using an anonymous function
$di->set("db", function(){
return new Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "blog"
));
});
以上這兩種服務的注冊方式產生相同的結果。然後,通過數組定義的,在後面需要的時候,你可以修改服務參數:
$di->setParameter("db", 0, array(
"host" => "localhost",
"username" => "root",
"password" => "secret"
));
從容器中獲得服務的最簡單方式就是使用」get」方法,它將從容器中返回一個新的實例:
$request = $di->get("request");
或者通過下面這種魔術方法的形式調用:
$request = $di->getRequest();
Phalcon\DI 同時允許服務重用,為了得到一個已經實例化過的服務,可以使用 getShared() 方法的形式來獲得服務。
具體的 Phalcon\Http\Request 請求示例:
$request = $di->getShared("request");
參數還可以在請求的時候通過將一個數組參數傳遞給構造函數的方式:
$component = $di->get("MyComponent", array("some-parameter", "other"));

6. PHP代碼網站如何防範SQL注入漏洞攻擊建議分享

做為網路開發者的你對這種黑客行為恨之入骨,當然也有必要了解一下SQL注入這種功能方式的原理並學會如何通過代碼來保護自己的網站資料庫。今天就通過PHP和MySQL資料庫為例,分享一下我所了解的SQL注入攻擊和一些簡單的防範措施和一些如何避免SQL注入攻擊的建議。
簡單來說,SQL注入是使用代碼漏洞來獲取網站或應用程序後台的SQL資料庫中的數據,進而可以取得資料庫的訪問許可權。比如,黑客可以利用網站代碼的漏洞,使用SQL注入的方式取得一個公司網站後台資料庫里所有的數據信息。拿到資料庫管理員登錄用戶名和密碼後黑客可以自由修改資料庫中的內容甚至刪除該資料庫。SQL注入也可以用來檢驗一個網站或應用的安全性。SQL注入的方式有很多種,但本文將只討論最基本的原理,我們將以PHP和MySQL為例。本文的例子很簡單,如果你使用其它語言理解起來也不會有難度,重點關注SQL命令即可。
一個簡單的SQL注入攻擊案例
假如我們有一個公司網站,在網站的後台資料庫中保存了所有的客戶數據等重要信息。假如網站登錄頁面的代碼中有這樣一條命令來讀取用戶信息。
$q
=
"SELECT
`id`
FROM
`users`
WHERE
`username`=
'
"
.$_GET['username'].
"
'
AND
`password`=
'
"
.$_GET['password'].
"
'
";?>現在有一個黑客想攻擊你的資料庫,他會嘗試在此登錄頁面的用戶名的輸入框中輸入以下代碼:
'
;
SHOW
TABLES;
點擊登陸鍵,這個頁面就會顯示出資料庫中的所有表。如果他現在使用下面這行命令:
';
DROP
TABLE
[table
name];
這樣他就把一張表刪除了!
防範SQL注入
-
使用mysql_real_escape_string()函數
在資料庫操作的代碼中用這個函數mysql_real_escape_string()可以將代碼中特殊字元過濾掉,如引號等。如下例:
$q
=
"SELECT
`id`
FROM
`users`
WHERE
`username`=
'
"
.mysql_real_escape_string(
$_GET['username']
).
"
'
AND
`password`=
'
"
.mysql_real_escape_string(
$_GET['password']
).
"
'
";?>防範SQL注入
-
使用mysql_query()函數
mysql_query()的特別是它將只執行SQL代碼的第一條,而後面的並不會執行。回想在最前面的例子中,黑客通過代碼來例後台執行了多條SQL命令,顯示出了所有表的名稱。所以mysql_query()函數可以取到進一步保護的作用。我們進一步演化剛才的代碼就得到了下面的代碼:
//connection
$database
=
mysql_connect("localhost",
"username","password");
//db
selection
$q
=
mysql_query("SELECT
`id`
FROM
`users`
WHERE
`username`=
'
"
.mysql_real_escape_string(
$_GET['username']
).
"
'
AND
`password`=
'
"
.mysql_real_escape_string(
$_GET['password']
).
"
'
",
$database);?>除此之外,我們還可以在PHP代碼中判斷輸入值的長度,或者專門用一個函數來檢查輸入的值。所以在接受用戶輸入值的地方一定要做好輸入內容的過濾和檢查。當然學習和了解最新的SQL注入方式也非常重要,這樣才能做到有目的的防範。如果使用的是平台式的網站系統如Wordpress,要注意及時打上官方的補丁或升級到新的版本。

7. PHP防SQL注入問題

你說的只是php代碼中可能會允許你使用注入語句,但是一般來說,網站防注入都是在鏈接資料庫的類中加入了轉換,也就是說把注入語句的關鍵字都加上了轉義字元。比如你遇到的這種情況,就是被防注入了。
關於你這個問題:
問:輸入框中的SQL語句應該如何寫?
條件:資料庫表、欄位全已知,輸入框長度不限。
我只能跟你說,你可以在輸入框中加入;,/這種符號,讓語句解析的時候出現問題,讓php把sql語句拼合成兩個或兩個以上。這樣你就可以在第二條語句之後加入你想要執行的命令了。
如果這種方法沒有效果,你只能使用溢出的方式來注入!
如果幫助到您,請記得採納為滿意答案哈,謝謝!祝您生活愉快!
vae.la

8. php注入函數到底能不能注入

php 5.00 版本以上自帶防注入功能。
所謂的SQL(結構化查詢語言)注入,簡單來說就是利用SQL語句在外部對SQL資料庫進行查詢,更新等動作。

9. 這樣的php代碼能不能被SQL注入攻擊

base64_encode 不能有效的防禦sql注入
看下php的文檔有段描述
Base64-encoded data takes about 33% more space than the original data.
就是encode後的內容比原來的內容要多佔33%的空間
真的要預防sql注入還是用 預處理 用php中的 pdo或者mysqli都支持預處理

10. PHP 被注入代碼,要如何解決

對表單提交信息進行字元串檢查,替換'等字元

熱點內容
esp32搭建自己的伺服器 發布:2025-02-05 18:58:00 瀏覽:317
wampphp升級 發布:2025-02-05 18:50:53 瀏覽:918
源碼地帶 發布:2025-02-05 18:46:37 瀏覽:613
我的世界伺服器怎麼騎別人的頭 發布:2025-02-05 18:46:32 瀏覽:89
怎麼卸載ftp賬號 發布:2025-02-05 18:41:52 瀏覽:62
SQL指定的服務並未以 發布:2025-02-05 18:40:09 瀏覽:972
電腦連接不了伺服器什麼意思 發布:2025-02-05 18:34:46 瀏覽:355
2015版dw怎麼配置站點 發布:2025-02-05 18:33:37 瀏覽:429
php數組中重復值 發布:2025-02-05 18:16:59 瀏覽:366
分布式存儲優點 發布:2025-02-05 18:15:29 瀏覽:644