Summary of PHP Development security issues _ PHP Tutorial

Source: Internet
Author: User
Tags md5 hash
Summary of PHP Development security issues. Summary of PHP Development security issues php gives developers great flexibility, but it also brings potential risks to security issues. we need to summarize previous problems in the near future, summary of PHP Development Security issues

Php provides developers with great flexibility, but it also brings potential risks to security issues. we need to summarize the previous problems in the near future, here, I would like to summarize some of my development feelings by translating an article.


When developing an Internet service, you must always keep in mind the security concept and embody it in the developed code. The PHP scripting language is not concerned with security issues, especially for most inexperienced developers. Every time you talk about any transactions involving money and transactions, you need to pay special attention to security issues, such as developing a forum or a shopping cart.

General points of security protection

Do not trust the form

For general Javascript front-end verification, the user's behavior cannot be known, for example, the javascript engine of the browser is closed, so that malicious data is sent to the server through POST. Verify the data transmitted to each php script on the server to prevent XSS attacks and SQL injection.

Do not trust users

Assume that every piece of data received by your website has malicious code and hidden threats. clean up every piece of data.

Disable global variables

Configure the following in the php. ini file:

Register_globals = Off

If this configuration option is enabled, there will be a great security risk. For example, a script file of process. php inserts the received data into the database. the form for receiving user input data may be as follows:

In this way, when the data is submitted to the process. php registers a $ username variable and submits the variable data to process. php. this variable is set for any POST or GET request parameters. If initialization is not performed on the display, the following problems will occur:

  1. // Define $authorized = true only if user is authenticated
  2. if (authenticated_user()) {
  3. $authorized = true;
  4. }
  5. ?>

Assume that the authenticated_user function is used to determine the value of the $ authorized variable. if the register_globals configuration is enabled, any user can send a request, to set the value of the $ authorized variable to any value to bypass this verification.

All the submitted data should be obtained through the predefined global array in PHP, including $ _ POST, $ _ GET, $ _ FILES, $ _ SERVER, $ _ REQUEST, etc, $ _ REQUEST is a federated variable of $ _ GET/$ _ POST/$ _ COOKIE arrays. the default sequence is $ _ COOKIE, $ _ POST, and $ _ GET.

  • Recommended security configuration options

Error_reporting is set to Off: do not expose error information to users. you can set it to ON during development.

Set safe_mode to Off.

Set register_globals to Off.

Disable the following functions: system, exec, passthru, shell_exec, proc_open, and popen.

Open_basedir is set to/tmp, so that session information can be stored and a separate website root directory can be set.

Set expose_php to Off

Set allow_url_fopen to Off.

Set allow_url_include to Off.

SQL injection attacks

Pay special attention to security when operating SQL statements in the database, because the user may enter a specific statement to change the functions of the original SQL statement. For example:

$ SQL = "select * from pinfo where product = '$ product '";

In this case, if the $ product parameter you enter is:

39 '; DROP pinfo; SELECT 'foo

The final SQL statement will look like the following:

Select product from pinfo where product = '39 '; DROP pinfo; SELECT 'foo'

In this way, three SQL statements will be generated, and the pinfo table will be deleted, which will cause serious consequences.

This problem can be solved simply by using the built-in functions of PHP:

  1. $sql = 'Select * from pinfo where product = '"'
  2. mysql_real_escape_string($product) . '"';

To prevent SQL injection attacks, you must do the following:

Type verification is always performed on input parameters.

Use the mysql_real_escape_string function to escape special characters such as single quotes, double quotes, and backquotes.

However, based on development experience, do not enable Magic Quotes of php. this feature has been abolished in php6 and is always escaped as needed.

Prevent basic XSS attacks

XSS attacks are not like other attacks. these attacks are carried out on the client. the most basic XSS tool is to prevent a javascript script from stealing the data and cookies submitted by the user on the form page to be submitted by the user.

XSS tools are more difficult to defend against than SQL injection, and websites of major companies have been attacked by XSS. Although such attacks are irrelevant to the php language, however, php can be used to filter user data to protect user data. here, we mainly use to filter user data. generally, HTML tags, especially a tags, are filtered out. The following is a common filtering method:

  1. function transform_HTML($string, $length = null) {
  2. // Helps prevent XSS attacks
  3. // Remove dead space.
  4. $string = trim($string);
  5. // Prevent potential Unicode codec problems.
  6. $string = utf8_decode($string);
  7. // HTMLize HTML-specific characters.
  8. $string = htmlentities($string, ENT_NOQUOTES);
  9. $string = str_replace("#", "#", $string);
  10. $string = str_replace("%", "%", $string);
  11. $length = intval($length);
  12. if ($length > 0) {
  13. $string = substr($string, 0, $length);
  14. }
  15. return $string;
  16. }

This function converts special characters in HTML to HTML objects. the browser displays the special characters in plain text when rendering the text. For exampleBoldWill be displayed:


The core of the above function is the htmlentities function. this function converts special html tags to html entity characters, which can filter most XSS attacks.

But for experienced XSS attackers, there is a more clever way to attack: use hexadecimal or UTF-8 encoding for their malicious code, instead of common ASCII text, for example, you can use the following method:

In this way, the result of browser rendering is:

SCRIPT Dosomethingmalicious SCRIPT

In this way, the attack is achieved. To prevent this, you need to convert # and % to their corresponding entity symbols based on the transform_HTML function, and add the $ length parameter to limit the maximum length of the submitted data.

Use SafeHTML to prevent XSS attacks

The above protection against XSS attacks is very simple, but does not contain all the user's tags. at the same time, there are hundreds of methods to bypass the filter function to submit javascript code, and there is no way to completely stop this situation.

At present, there is no single script to ensure that the attack will not break through, but there is always a relatively better degree of protection. There are two security protection methods: whitelist and blacklist. The whitelist is simpler and more effective.

A whitelist solution is SafeHTML, which is smart enough to identify valid HTML and then can remove any dangerous tags. This needs to be parsed based on the HTMLSax package.

How to install and use SafeHTML:

1. go to Page = safehtml download the latest SafeHTML

2. put the file into the server's classes directory, which contains all the SafeHTML and HTMLSax libraries.

3. include the SafeHTML class file in your script

4. create a SafeHTML object

5. use the parse method for filtering

  1. /* If you're storing the HTMLSax3.php in the /classes directory, along
  2. with the safehtml.php script, define XML_HTMLSAX3 as a null string. */
  3. define(XML_HTMLSAX3, '');
  4. // Include the class file.
  5. require_once('classes/safehtml.php');
  6. // Define some sample bad code.
  7. $data = "This data would raise an alert 《script》alert('XSS Attack')《script》";
  8. // Create a safehtml object.
  9. $safehtml = new safehtml();
  10. // Parse and sanitize the data.
  11. $safe_data = $safehtml->parse($data);
  12. // Display result.
  13. echo 'The sanitized data is
    ' . $safe_data;
  14. ?>

SafeHTML does not completely prevent XSS attacks, but is a relatively complex method of script testing.

Use one-way HASH encryption to protect data

One-way hash encryption ensures that each user's password is unique and cannot be decrypted. only the end user knows the password and the system does not know the original password. One advantage is that after the system is attacked, attackers cannot know the original password data.

Encryption and Hash are two different processes. Unlike encryption, Hash cannot be decrypted and is unidirectional. at the same time, two different strings may obtain the same hash value, which cannot guarantee the uniqueness of the hash value.

The hash value processed by the MD5 function cannot be cracked, but it is always possible, and there is also an MD5 hash dictionary on the Internet.

Use mcrypt to encrypt data

The MD5 hash function can display data in a readable form. However, when storing users' credit card information, you need to encrypt and store it, and then decrypt it.

The best way is to use the mcrypt module, which contains more than 30 encryption methods to ensure that only the Encryptor can decrypt the data.

  1. $data = "Stuff you want encrypted";
  2. $key = "Secret passphrase used to encrypt your data";
  3. $cipher = "MCRYPT_SERPENT_256";
  4. $mode = "MCRYPT_MODE_CBC";
  5. function encrypt($data, $key, $cipher, $mode) {
  6. // Encrypt data
  7. return (string)
  8. base64_encode
  9. (
  10. mcrypt_encrypt
  11. (
  12. $cipher,
  13. substr(md5($key),0,mcrypt_get_key_size($cipher, $mode)),
  14. $data,
  15. $mode,
  16. substr(md5($key),0,mcrypt_get_block_size($cipher, $mode))
  17. )
  18. );
  19. }
  20. function decrypt($data, $key, $cipher, $mode) {
  21. // Decrypt data
  22. return (string)
  23. mcrypt_decrypt
  24. (
  25. $cipher,
  26. substr(md5($key),0,mcrypt_get_key_size($cipher, $mode)),
  27. base64_decode($data),
  28. $mode,
  29. substr(md5($key),0,mcrypt_get_block_size($cipher, $mode))
  30. );
  31. }
  32. ?>

The mcrypt function requires the following information:

1. data to be encrypted

2. key used to encrypt and decrypt data

3. cipher, a specific algorithm for user-selected data encryption, as shown in figureMCRYPT_TWOFISH192, MCRYPT_SERPENT_256,MCRYPT_RC2,MCRYPT_DES, AndMCRYPT_LOKI97)

4. encryption mode

5. the seed of encryption is used to start the data in the encryption process. it is an additional binary data used to initialize the encryption algorithm.

6. the encryption key and seed length can be obtained using the mcrypt_get_key_size function and the mcrypt_get_block_size function.

If both the data and key are stolen, attackers can traverse the ciphers to find the path. Therefore, we need to perform MD5 for the encrypted key to ensure security. At the same time, the encrypted data returned by the mcrypt function is a binary data, which will cause other errors when saved to the database field. base64encode is used to convert the data to a hexadecimal number for easy storage.


Php gives developers great flexibility, but it also brings potential risks to security issues. we need to summarize the previous problems in the near future. here...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.