How to prevent code injection attacks in PHP?

I'm a little confused, there are so many functions in PHP, and some use it, some use it. Some people use: htmlspecialchars() , htmlentities() , strip_tags() etc.

What is right and what do you guys usually use?

Is this correct (advise me better, if any):

 $var = mysql_real_escape_string(htmlentities($_POST['username'])); 

Can this line prevent a MySQL attack and an XSS attack?

By the way, are there other things I need to pay attention to besides XSS attacks and MySQL injections?

EDIT

To conclude:

If I want to insert a row into the database, I do not need to use htmlentities , just use mysql_real_escape_string . When displaying data, use htmlentities() , is that what you all mean?

Summarize:

  • mysql_real_escape_string used when pasting into a database
  • htmlentities() used when displaying data on a web page
  • htmlspecialchars() used when?
  • strip_tags() used when?
  • addslashes() used when?

Can someone fill out a question mark?

+48
php code-injection
Jul 30 '09 at 11:04
source share
8 answers
  • mysql_real_escape_string used when pasting into a database
  • htmlentities() used when displaying data on a web page
  • htmlspecialchars() used when?
  • strip_tags() used when?
  • addslashes() used when?

htmlspecialchars () is used when?

htmlspecialchars about the same as htmlentities . Difference: character encoding.

Both controls encode characters, such as < , > , & , etc., are used to open labels, etc. htmlentities also encode characters from other languages, such as umlauts euro-symbols and the like. If your sites are UTF, use htmlspecialchars() , otherwise use htmlentities() .

strip_tags () is used when?

htmlspecialchars / entities encode special characters, so they are displayed but not interpreted. strip_tags DELETES them.

In practice, it depends on what you need to do.

Example: you encoded a forum and provided users with a text box so that they can publish materials. Attackers just try:

 pictures of <a href="javascript:void(window.setInterval(function () {window.open('http://evil.com');}, 1000));">kittens</a> here 

If you do nothing, a link will be displayed, and the victim who clicks on the link receives a lot of pop-ups.

If you htmlentity / htmlspecialchar your conclusion, the text will be there as it is. If you strip_tag, it just removes the tags and displays them:

 pictures of kittens here 

Sometimes you may need a mixture, leave tags there, for example <b> ( strip_tags can leave specific tags there). This is also unsafe, so it is better to use the library with the full version for XSS.

addslashes

To quote an old version of the PHP manual :

Returns a string with backslashes before the characters that should be specified in database queries, etc. These characters are single quotes ('), double quotes ("), backslashes (), and NUL ( NULL bytes).

An example of using addlashes () is when you enter data into a database. For example, to insert the name O'reilly into the database, you would need to avoid it. He strongly recommended using the DBMS escape function (for example, mysqli_real_escape_string () for MySQL or pg_escape_string () for PostgreSQL), but if the DBMS used does not have an evacuation function and the DBMS uses \ to escape special characters, you can use this function.

The current version is written in different ways.

+58
Jul 30 '09 at 13:02
source share
— -

Encode data only in the place where it enters the system that you need to encode for - otherwise you will encounter situations when you want to manipulate real data.

For SQL injection - use related variables as described in How can I prevent SQL injection in PHP? (he talks about prepared statements, but it's a binding that gives you protection, not preparation).

For XSS - if you write in HTML at the point where the HTML or text is specified. Use htmlentities where you create the document. I would not want to store the data in this form in a database (except, perhaps, in a system with frequent recording with rarely read frequencies, when the performance and CPU access time / disk access time became and issued - then I would have raw_ and html_ version of the column ... or just use memcached or the like).

If you allow users to enter URLs, you need to be more careful, since javascript:do_evil() is a valid URI that will be executed (for example, as an href for link to a link or (in some browsers) src images that are just loaded )

+6
Jul 30 '09 at 11:09
source share

I thought of this quick checklist:

  • Always use HTTPS, without HTTPS your site is completely unencrypted . And no, client-side encryption of things and sending them will not work, think about it. Invalid HTTPS certificates also make you vulnerable to a MITM attack . Just use Let Encrypt if you cannot afford a certificate.
  • Always use htmlspecialchars() on any output from your PHP code, that is, or it contains user input . Most template engines help you do this easily.
  • Use the HTTP-only flag in php.ini to prevent scripts from accessing your cookies.
  • Preventing session related issues
    • Never expose the user PHPSESSID (session identifier) ​​outside the cookie , if someone recognizes the session identifier of someone else, he can simply use it to log in to his account
    • Be very careful with the " Remember me maybe warn a little."
    • Update session id on user login (or something suitable)
    • Inactive Session Timeout
  • Never trust a cookie, it can be modified, deleted, modified and created by a script / user at any time
  • Prevent SQL related issues
    • Always use prepared statements . Prepared statements force user data to be entered separately and prevent SQL injection
    • Make code by throwing an exception when it doesn't work. Sometimes your SQL server may be unavailable for some reason, libraries like PDO ignore this error by default and log a warning in the logs. This leads to the fact that the variables that you get from the database are zero, depending on your code, this can cause a security problem.
    • Some libraries, such as PDO imitate prepared statements. Turn it off.
    • Use UTF-8 in your databases, it allows you to store almost any character and avoid encoding-related attacks
    • Never associate anything with your request . Things like $myquery = "INSERT INTO mydb.mytable(title) VALUES(". $user_input. ")" much mean that you have a huge risk for SQL injection.
  • Store downloaded files in random names without extension. If the user downloads a file with the extension .php file, then whenever your code loads this file, it executes it and allows the user to execute some code
  • Make sure you are not vulnerable to a CSRF attack .
  • Always keep your copy of PHP up to date for the latest security fixes and performance improvements.
+6
Jun 16 '16 at 1:24
source share

htmlspecialchars() turns & , ' , " , < and > into HTML entity format ( &amp; htmlspecialchars() &quot; etc.),

htmlentities() turns all applicable characters into their HTML entity format.

strip_tags() removes all HTML and PHP tags.

Both htmlspecialchars() and htmlentities() accept an optional parameter that indicates how to handle quotes. See the PHP manual for specifics.

The strip_tags() function accepts an optional parameter that indicates which tags should not be removed.

  $var = strip_tags ($var, '<p><br />'); 

The strip_tags() function will remove even invalid HTML tags, which can cause problems. For example, strip_tags() all the code that, in his opinion, is an HTML tag, even if it is not formed correctly, for example

 <b I forgot to close the tag. 
+4
Apr 13 '11 at 16:24
source share

You need to use mysql_escape_string () when pasting into the database and htmlentites when displaying HTML. This is enough if you want to prevent a simple injection attack, but there are no doubts about many other security issues that you should be aware of when developing a web application, another important of which are fakes with cross-site requests.

+3
Jul 30 '09 at 11:08
source share

I would not use htmlentities () when pasting data into a database or in a database query. If the data in your database is stored as entities, then this data is only useful for what html objects understand.

You need to use different screening mechanisms for different types of output, for example. SQL - mysql_real_escape_string () , HTML - htmlentities () or htmlspecialchars () , shell - escapeshellarg () . This is because the characters that are “dangerous” are different for each of them - there is no magic way to make any data safe for any output medium.

+2
Jul 30 '09 at 11:11
source share

Take a look at this PHP Security Consortium website. I found this to be a good site for a general overview of PHP security (including SQL Injection and XSS).

+1
Jul 30 '09 at 11:07
source share

I know this is an old question, but nowadays the most voted answer can be misleading for beginners.

Since 2017

  • You should never use mysql_real_escape_string. Even mysqli_real_escape_string is too weak to protect your database from SQL injection. Instead, you should use PDO and similar methods. (see this manual )

  • XSS (here I mean: strip_tags() , addslashes() , htmlspecialchars() , htmlentities() ) - here the most voted answer is still correct, but I would suggest reading this article

+1
Dec 10 '17 at 22:14
source share



All Articles