PHP common security problems and solutions

1, SQL injection

SQL injection is one of the biggest threats to your site, if your database by others SQL injection attacks, others can turn out your database, and perhaps more serious consequences.

Solution:

There are two main solutions. The user input data or the escape packaged using statement. The method of escaping the package is a good function, is used to filter the data submitted by the user, to remove unwanted tags. However, I do not recommend using this method, it is more easy to forget that in every place to do this deal.

Below, I'll describe how to use PDO to perform packaged statement (mysqi, too):

1

2

3

4

5

6

7

$username = $_GET['username'];

  

$query = $pdo->prepare('SELECT * FROM users WHERE username = :username');

  

$query->execute(['username' => $username]);

  

$data = $query->fetch();

2、XSS

XSS also known as CSS (Cross Site Script), cross-site scripting attacks. It refers to a malicious attacker to insert malicious Web page in html code, when a user browsing the page, embedded Web inside the html code will be executed to achieve the malicious user's specific purpose.

Solution:

Determined not to believe any input from the user, and filter out all the special characters in the input. This will eliminate most of the XSS attacks:

1

2

3

<?php

  

$searchQuery = htmlentities($searchQuery, ENT_QUOTES);

Or you can use a template engine, Twig, general template engine will default output plus htmlentities prevention.

3、XSRF/CSRF

CSRF CSRF is an abbreviation, it is the attacker through a number of techniques to trick users to visit the site and once certified to run some operations.

Solution:

The most common method is to generate a defense CSRF encrypted security token string, generally referred to as Token, and the Token or Cookie stored in the Session.

Every time you build forms in a Web page, Token Token will be placed in hidden fields in the form, the form will be based on the user's Cookie or Session in the Token Token comparison, verification succeeds only be given after a request by the server.

Since the attacker can not know the contents of Token token (Token token each form are random), and therefore can not impersonate the user.

Guess you like

Origin www.cnblogs.com/heyue0117/p/11827687.html