Home Backend Development PHP Tutorial php filter special characters sql anti-injection code

php filter special characters sql anti-injection code

Jul 25, 2016 am 08:54 AM

  1. //Method one
  2. //Filter',",sql language name
  3. addslashes();
  4. //Method two, remove all html tags
  5. strip_tags();
  6. //Method three Filtering may generate code
  7. function php_sava($str)
  8. {
  9. $farr = array(
  10. "/s+/",
  11. "/<(/?)(script|i?frame|style|html|body|title| link|meta|?|%)([^>]*?)>/isU",
  12. "/(<[^>]*)on[a-zA-Z]+s*=([ ^>]*>)/isU",
  13. );
  14. $tarr = array(
  15. " ",
  16. "<>", //If you want to directly clear unsafe tags, you can leave it blank here
  17. "" ,
  18. );
  19. $str = preg_replace( $farr,$tarr,$str);
  20. return $str;
  21. }
  22. //php sql anti-injection code
  23. class sqlin
  24. {
  25. //dowith_sql($value)
  26. function dowith_sql($str)
  27. {
  28. $str = str_replace("and","",$str);
  29. $str = str_replace("execute","",$str);
  30. $str = str_replace("update" ,"",$str);
  31. $str = str_replace("count","",$str);
  32. $str = str_replace("chr","",$str);
  33. $str = str_replace("mid ","",$str);
  34. $str = str_replace("master","",$str);
  35. $str = str_replace("truncate","",$str);
  36. $str = str_replace(" char","",$str);
  37. $str = str_replace("declare","",$str);
  38. $str = str_replace("select","",$str);
  39. $str = str_replace( "create","",$str);
  40. $str = str_replace("delete","",$str);
  41. $str = str_replace("insert","",$str);
  42. $str = str_replace ("'","",$str);
  43. $str = str_replace(""","",$str);
  44. $str = str_replace(" ","",$str);
  45. $str = str_replace ("or","",$str);
  46. $str = str_replace("=","",$str);
  47. $str = str_replace("%20","",$str);
  48. // echo $str;
  49. return $str;
  50. }
  51. //aticle() anti-SQL injection function//php tutorial
  52. function sqlin()
  53. {
  54. foreach ($_GET as $key=>$value)
  55. {
  56. $ _GET[$key]=$this->dowith_sql($value);
  57. }
  58. foreach ($_POST as $key=>$value)
  59. {
  60. $_POST[$key]=$this->dowith_sql( $value);
  61. }
  62. }
  63. }
  64. $dbsql=new sqlin();
  65. ?>
Copy code

Usage: Copy the above code to create a new sqlin.php file, and then include it in the page where GET or POST data is received

Principle analysis: Replace all SQL keywords with empty This code cannot be used in the guestbook. If you want to use it in the guestbook, please replace it. ....... $str = str_replace("and","",$str); arrive $str = str_replace("%20","",$str); ... The code is:

  1. $str = str_replace("and","and",$str);
  2. $str = str_replace("execute","execute",$str);
  3. $str = str_replace ("update","update",$str);
  4. $str = str_replace("count","count",$str);
  5. $str = str_replace("chr","c hr",$str);
  6. $str = str_replace("mid","mid",$str);
  7. $str = str_replace("master","master",$str);
  8. $str = str_replace(" truncate","truncate",$str);
  9. $str = str_replace("char","char",$str);
  10. $str = str_replace("declare","declare",$str) ;
  11. $str = str_replace("select","select",$str);
  12. $str = str_replace("create","create",$str);
  13. $str = str_replace("delete" ,"delete",$str);
  14. $str = str_replace("insert","insert",$str);
  15. $str = str_replace("'","'",$str);
  16. $ str = str_replace(""",""",$str);
  17. ?>
Copy code

------------------------------------------------- ------ addslashes – Use backslashes to quote strings

string addslashes ( string str )

Returns a string with backslashes added in front of certain characters for database query statements, etc. These characters are single quote ('), double quote ("), backslash () and NUL (NULL character).

An example of using addslashes() is when you are entering data into a database. For example, inserting the name O'reilly into the database requires escaping it. Most databases use as escape character: O'reilly. This puts the data into the database without inserting extra . When the PHP directive magic_quotes_sybase is set to on, it means that inserting ' will be escaped with '.

By default, the PHP instruction magic_quotes_gpc is on, which mainly automatically runs addslashes() on all GET, POST and COOKIE data. Do not use addslashes() on strings that have been escaped by magic_quotes_gpc, as this will result in double escaping. When encountering this situation, you can use the function get_magic_quotes_gpc() to detect it. get_magic_quotes_gpc() This function obtains the value of the variable magic_quotes_gpc (GPC, Get/Post/Cookie) in the PHP environment configuration. Returning 0 means turning off this function; returning 1 means turning this function on. When magic_quotes_gpc is turned on, all ' (single quote), " (double quote), (backslash) and null characters are automatically converted to overflow characters containing backslashes. addslashes and stripslashes are used to operate on database characters in PHP. At first glance, it seems difficult to remember, but if you analyze it, add means to add, and strip means to ignore. slash is a slash, and slash is the plural of slash. Then addslashes means adding a slash, because some special characters are written to the database. Problems will occur later, such as " ', etc., so special symbols must be escaped to tell the database that those special symbols are strings. In the same way, stripslashes must subtract the slash when fetching the string from the database. htmlspecialchars converts certain special characters into html encoding. The most commonly used occasion may be the message board that handles customer messages. These special characters are limited to the following: & -> & " -> " < > -> > The functions of htmlentities are similar to htmlspecialchars, but htmlentities ignores all entities defined by HTML, including various special characters and Chinese characters. The result is that the Chinese characters become a bunch of garbled characters. htmlspecialchars_decode is the reverse process of htmlspecialchars, which converts html encoding into characters. PHP utility function for filtering special characters Special character filtering method for php form submission html special character filter php class How to escape special characters in url links Detailed explanation of php special character escaping php filter parameter special characters anti-injection php method to filter illegal and special strings Examples of php special character processing functions



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles