Several methods to prevent SQL injection in php
- /**
- * SQL Injection Prevention
- * @ Author: test@jbxue.com
- **/
- /**
- * Reject SQL inject
- */
- If (! Function_exists (quote ))
- {
- Function quote ($ var)
- {
- If (strlen ($ var ))
- {
- $ Var =! Get_magic_quotes_gpc ()? $ Var: stripslashes ($ var );
- $ Var = str_replace ("'", "\'", $ var );
- }
- Return "'$ var '";
- }
- }
- If (! Function_exists (hash_num )){
- Function hash_num ($ input)
- {
- $ Hash = 5381;
- For ($ I = 0; $ I <strlen ($ str); $ I ++)
- {
- $ C = ord ($ str {$ I });
- $ Hash = ($ hash <5) + $ hash) + $ c;
- }
- Return $ hash;
- }
- }
- ?>
Test:
- /**
- * Anti-SQL Test Code
- Create table if not exists 'TB '(
- 'Id' int (10) unsigned not null auto_increment,
- 'Age' tinyint (3) unsigned not null,
- 'Name' char (100) not null,
- 'Note' text not null,
- Primary key ('id ')
- ) ENGINE = MyISAM default charset = utf8;
- **/
- Include_once ('Common. php ');
- Var_dump (hash_num ('ddddd '));
- If (empty ($ _ GET ))
- {
- $ _ GET = array ('age' => '99', 'name' => 'A \ 'B \ 'C ";', 'note' => "A' B \ '\ nC #");
- }
- $ Age = (int) $ _ GET ['age'];
- $ Name = quote ($ _ GET ['name']);
- $ Note = quote ($ _ GET ['note']);
- $ SQL = "INSERT INTO 'TB' ('age', 'name', 'note') VALUES
- ($ Age, $ name, $ note )";
- Var_dump ($ SQL );
- ?>
# ------------------ Method 2:
$ Magic_quotes_gpc = get_magic_quotes_gpc ();
- @ Extract (daddslashes ($ _ COOKIE ));
- @ Extract (daddslashes ($ _ POST ));
- @ Extract (daddslashes ($ _ GET ));
- If (! $ Magic_quotes_gpc ){
- $ _ FILES = daddslashes ($ _ FILES );
- }
Function daddslashes ($ string, $ force = 0 ){
- If (! $ GLOBALS ['Magic _ quotes_gpc '] | $ force ){
- If (is_array ($ string )){
- Foreach ($ string as $ key => $ val ){
- $ String [$ key] = daddslashes ($ val, $ force );
- }
- } Else {
- $ String = addslashes ($ string );
- }
- }
- Return $ string;
- }
- ?>
Method 3:
- Function inject_check ($ SQL _str) {// prevents injection
- $ Check = eregi ('select | insert | update | delete | '|/* | .. /|. /| union | into | load_file | outfile ', $ SQL _str );
- If ($ check ){
- Echo "illegal injection content entered! ";
- Exit ();
- } Else {
- Return $ SQL _str;
- }
- }
- Function checkurl () {// check the origin path
- If (preg_replace ("/https tutorial? : // ([^:/] +). */I "," 1 ", $ _ server ['http _ referer'])! = Preg_replace ("/([^:] +). */", "1", $ _ server ['http _ host']) {
- Header ("location: http://s.jbxue.com ");
- Exit ();
- }
- }
- // Call
- Checkurl ();
- $ Str = $ _ get ['URL'];
- Inject_check ($ SQL _str); // you can perform this operation when obtaining the parameter.
|