search
HomeBackend DevelopmentPHP TutorialSolve several common attack methods in PHP website development

Solve several common attack methods in PHP website development

Mar 08, 2018 pm 01:12 PM
phpattackwebsite development

This article mainly shares with you several common attack methods to solve PHP website development. Common security threats in PHP website construction include: SQL injection, manipulation of GET and POST variables, buffer overflow attacks, cross-site scripting attacks, browser Data manipulation and remote form submission within.

1. Prevent SQL injection attacks

In SQL injection attacks, users add information to database queries by manipulating forms or GET query strings.

For example, assume you have a simple login database. Each record in this database has a username field and a password field. Build a login form to allow users to log in.

The solution to this problem is to use PHP's built-in mysql_real_escape_string() function as a wrapper around any user input.

This function escapes characters in a string, making it impossible for the string to pass special characters such as apostrophes and allowing MySQL to operate based on special characters. Listing 7 shows the escaped code.

2. Prevent users from manipulating variables

Just because a user has a valid password does not mean that he will act according to the rules - he has many opportunities to cause damage. For example, an application might allow users to view special content.

For example template.php?pid=33 or template.php?pid=321. The part of the URL after the question mark is called the query string. Because the query string is placed directly in the URL, it is also called a GET query string.

Is there anything wrong here?

First of all, there is an implicit belief that the GET variable pid from the browser is safe.

What will happen?

Most users are not that smart and cannot construct semantic attacks. However, if they notice pid=33 in the browser's URL location field, they might start causing trouble.

If they enter another number, then it may be fine; but if they enter something else, such as entering an SQL command or the name of a file (such as /etc/passwd), or doing other mischief, such as Enter a value up to 3,000 characters long, and what happens?

In this case, remember the basic rule, don't trust user input.

Application developers know that the personal identifiers (PIDs) accepted by template.php should be numeric, so they can use PHP's is_numeric() function to ensure that non-numeric PIDs are not accepted.

All you need to do is use strlen() to check whether the length of the variable is non-zero; if so, use an all-numeric regular expression to ensure that the data element is valid. If the PID contains letters, slashes, periods, or anything resembling hexadecimal, then this routine captures it and blocks the page from user activity.

3. Buffer overflow attack

Buffer overflow attack attempts to make the PHP application (or more precisely, in Apache or the underlying operating system) A memory allocation buffer overflow occurred.

Remember, you may be writing your web application in a high-level language like PHP, but you still end up calling C (in the case of Apache). Like most low-level languages, C has strict rules for memory allocation.

Buffer overflow attacks send a large amount of data to the buffer, causing part of the data to overflow into adjacent memory buffers, thereby destroying the buffer or rewriting the logic. This can cause a denial of service, corrupt data, or execute malicious code on the remote server.
The only way to prevent buffer overflow attacks is to check the length of all user input.

Note that buffer overflow attacks are not limited to long strings of numbers or letters. You may also see long hexadecimal strings (often looking like \xA3 or \xFF).

Remember, the goal of any buffer overflow attack is to flood a specific buffer and place malicious code or instructions into the next buffer, thereby corrupting data or executing malicious code.

The simplest way to deal with hexadecimal buffer overflow is to not allow input to exceed a certain length.
If you are dealing with a form text area that allows longer entries in the database, there is no way to easily limit the length of the data on the client side. After the data reaches PHP, you can use regular expressions to clear out any hex-like strings.

4. Cross-site scripting attack

In a cross-site scripting (XSS) attack, a malicious user often enters information in a form (or through other user input methods), and these inputs will Malicious client-side tokens are inserted into processes or databases.

For example, let's say you have a simple guest book program on your site that allows visitors to leave their name, email address, and a brief message.

A malicious user could use this opportunity to insert something other than a brief message, such as an image that would be inappropriate for other users or JavaScript that would redirect the user to another site, or steal cookie information.

Fortunately, PHP provides the strip_tags() function, which can remove any content surrounded by HTML tags. The strip_tags() function also allows providing a list of allowed tags.

From a security perspective, using strip_tags() on public user input is necessary. If the form is in a protected area (such as a content management system) and you trust users to perform their tasks correctly (such as creating HTML content for a Web site), then using strip_tags() may be unnecessary and affect productivity .

There is another question: If you want to accept user input, such as comments on posts or guest registration items, and need to display this input to other users, then you must put the response in PHP's htmlspecialchars() in function.

This function converts the ampersand, symbols into HTML entities. For example, the ampersand (&) becomes &. In this case, even if the malicious content escapes the processing of strip_tags() on the front end, it will be processed by htmlspecialchars() on the back end.

5. Data manipulation in the browser

There is a type of browser plug-in that allows users to tamper with the header elements and form elements on the page. Using Tamper Data, a Mozilla plug-in, it's easy to manipulate simple forms with many hidden text fields to send instructions to PHP and MySQL.

Before the user clicks Submit on the form, he can start Tamper Data. When submitting the form, he will see a list of form data fields.

Tamper Data allows the user to tamper with this data before the browser completes the form submission.

The easiest way to defend against this tool is to assume that any user could potentially use Tamper Data (or a similar tool).

Provide only the minimum amount of information required by the system to process the form, and submit the form to some dedicated logic. For example, the registration form should only be submitted to the registration logic.

What if you have established a common form processing function and many pages use this common logic?

What should you do if you use hidden variables to control the flow direction?

For example, it may be specified in a hidden form variable which database table to write to or which file repository to use. There are 4 options:

Don't change anything and pray that there aren't any malicious users on the system.

Rewrite the function to use a safer dedicated form processing function and avoid using hidden form variables.

Use md5() or other encryption mechanisms to encrypt table names or other sensitive information in hidden form variables. Don't forget to decrypt them on the PHP side.

Obfuscate the meaning of values ​​by using abbreviations or nicknames, and then convert these values ​​in PHP form processing functions. For example, if you want to reference the users table, you can reference it with u or any string (such as u8y90×0jkL).

The latter two options are not perfect, but they are much better than having the user easily guess the middleware logic or data model.

6. Remote form submission

The advantage of the Web is that it can share information and services. The downside is sharing information and services because some people do things without any scruples.

Take the form as an example. Anyone can visit a Web site and create a local copy of the form using File > Save As on the browser. He can then modify the action parameter to point to a fully qualified URL (not to formHandler.php, but to http://www.yoursite.com/formHandler.php since the form is on this site) and do what he wants For any modification, click Submit, and the server will receive this form data as a legal communication flow.

First you may consider checking $_SERVER['HTTP_REFERER'] to determine whether the request comes from your own server. This method can block most malicious users, but it cannot block the most sophisticated hackers. These people are smart enough to tamper with the referrer information in the header to make the remote copy of the form look like it was submitted from your server.

A better way to handle remote form submission is to generate a token based on a unique string or timestamp and place this token in the session variable and the form. After submitting the form, check if the two tokens match. If it doesn't match, you know someone is trying to send data from a remote copy of the form.

PHP website development security summary:

Use mysql_real_escape_string() to prevent SQL injection problems.

Use regular expressions and strlen() to ensure that GET data has not been tampered with.

Use regular expressions and strlen() to ensure that user-submitted data does not overflow the memory buffer.

Use strip_tags() and htmlspecialchars() to prevent users from submitting potentially harmful HTML tags.

Prevent the system from being breached by tools like Tamper Data.

Use a unique token to prevent users from submitting forms to the server remotely.

Related recommendations:

How to implement form submission data verification function in php and prevent SQL injection and XSS attacks

How to prevent web attacks- -Security issues that PHP beginners need to know

Case analysis on how to batch block malicious IP addresses to prevent attacks under Linux

The above is the detailed content of Solve several common attack methods in PHP website development. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.