To ensure the security of user input in PHP, a cleaning function needs to be written to process input. The specific methods are as follows: 1. Use filter_var to perform basic cleaning, such as filtering HTML tags; 2. Select the corresponding filtering method according to the input type (such as mailbox, URL, integer, text); 3. Use batch processing functions for multi-field input to improve efficiency; 4. Note that back-end verification cannot rely on the front-end, avoid blacklisting strategies, combine parameterized query to prevent SQL injection, and clean data in context when output.
Processing user input is a link that cannot be avoided in any web application. Especially in PHP, unprocessed user input can easily cause security problems, such as SQL injection, XSS attacks, etc. Therefore, it is very necessary to write a reliable function to clean up (sanitize) user input.

The following function can basically cover most scenarios, have a clear structure, and is convenient for subsequent expansion.
1. Use filter_var
function for basic cleaning
The built-in filter_var
function in PHP is very practical and can clean and verify different types of data. For example, filtering mailboxes, URLs, integers, etc.

function sanitize_input($data) { return filter_var($data, FILTER_SANITIZE_STRING); }
The above function removes HTML tags and special characters from the data, and is suitable for most text inputs. But be aware that this function will not automatically process arrays or multi-layer data structures. If the array is passed in, additional processing is required.
Tips:
FILTER_SANITIZE_STRING
has been deprecated after PHP 8.1. It is recommended to usehtmlspecialchars()
or more specific filters, such asFILTER_SANITIZE_FULL_SPECIAL_CHARS
.
2. Different filtering methods should be used to process different types of inputs
Different input types should use different filtering rules, such as:
- Email: Use
FILTER_VALIDATE_EMAIL
- URL: Use
FILTER_VALIDATE_URL
- Integer: Use
FILTER_VALIDATE_INT
- General text: Use
htmlspecialchars()
orFILTER_SANITIZE_FULL_SPECIAL_CHARS
The function can be extended like this:
function sanitize_input($data, $type = 'string') { switch ($type) { case 'email': return filter_var($data, FILTER_VALIDATE_EMAIL); case 'url': return filter_var($data, FILTER_VALIDATE_URL); case 'int': return filter_var($data, FILTER_VALIDATE_INT); case 'string': default: return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8'); } }
In this way, you can choose a more accurate processing method according to the input type when using it, such as:
$email = sanitize_input($_POST['email'], 'email');
3. It can be batch processed when entering multiple fields
If you are processing form submissions, there are often multiple fields that need to be cleaned. You can write a helper function to batch process:
function sanitize_array($data, $rules = []) { $sanitized = []; foreach ($data as $key => $value) { $type = isset($rules[$key]) ? $rules[$key] : 'string'; $sanitized[$key] = sanitize_input($value, $type); } return $sanitized; }
Example of usage:
$form_data = [ 'name' => $_POST['name'], 'email' => $_POST['email'], 'age' => $_POST['age'] ]; $rules = [ 'name' => 'string', 'email' => 'email', 'age' => 'int' ]; $sanitized = sanitize_array($form_data, $rules);
This is safe and convenient to handle, and is easier to maintain.
4. Precautions and common misunderstandings
- Don't rely on front-end verification : front-end verification is just user experience optimization, and the back-end must be re-checked.
- Don't just filter "dangerous characters" : the blacklisting method is unreliable and easy to miss, and should be handled with whitelist or security functions.
- Preventing SQL injection requires parameterized queries : Cleaning up input is only the first step, and truly preventing SQL injection also depends on preprocessing statements from PDO or mysqli.
- It is also important to clean the output : for example, when outputting to HTML, JS, and CSS, you must use different functions (such as
htmlspecialchars
,json_encode
, etc.).
Basically that's it. Write a general and safe cleaning function, which is not complicated but is easy to ignore details. Use filter_var
and htmlspecialchars
well, and then judge with the specific input type, you can deal with most scenarios.
The above is the detailed content of php function to sanitize user input. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech
