search
HomeBackend DevelopmentPHP TutorialIllegal character filtering_PHP tutorial

Illegal character filtering_PHP tutorial

Jul 13, 2016 pm 05:09 PM
aspphpSamehostbutfunctioncharacterInfluenceThoughtarticleoffilter

Illegal character filteringThis article mainly talks about php filtering illegal charactersIt does not talk about the function of asp filtering illegal characters, but the idea is the same.

) Filter characters that affect the normal operation of MySQL.

When you need to substitute the content entered by the user (which may include single quotes, double quotes, backslashes, and the null character NUL) into the mysql statement for execution, you should set the magic_quotes_gpc item in APACHE to On.

If this item in APACHE is set to Off, the PHP function addslashes() can also be used to achieve the same purpose, but these two methods cannot be used at the same time, otherwise repeated substitutions will occur and errors will occur.

Sample:

PHP code

if (get_magic_quotes_gpc()) {

$content=$_POST["content"];

} else { 

$content=addslashes($_POST["content"]);



?>

Of course, if the magic_quotes_gpc item in APACHE is On, but sometimes you don’t want to escape the special characters of a certain item, you can use stripslashes() to remove the

2) Filter characters that affect the normal operation of MSSQL.

When you need to substitute the content entered by the user (which may include single quotes) into the mssql statement for execution, you should set the magic_quotes_sybase item in APACHE to On. At this time, the magic_quotes_gpc item will no longer take effect.

If this item in APACHE is set to Off, there is no suitable function in PHP to achieve the same purpose. You can only use the string replacement function to achieve this purpose.

Sample:

PHP code

$content=str_replace("'","''"$_POST["content"]); 

?>

Now PHP on 10.218.17.53 needs to access both mysql and mssql. The settings in APACHE cannot take into account both databases, so only mysql has been set accordingly.

2. A measure to deal with user input containing SQL statements.

The following two SQL writing methods are relatively common, but the security level is different. When the user submits $id='1 and 1=2 union select...', the first one will display something that should not be displayed. data, while the second type is relatively safer.

SQL code
Select * FROM article Where articleid=$id 
Select * FROM article Where articleid='$id'

3. Prevent the content entered by the user from affecting the normal display of the page due to the inclusion of html tags or javascript.

You can use htmlspecialchars() to filter the & "

PHP code
$content = htmlspecialchars($content);

4. When the content to be displayed on the page contains carriage returns and line breaks, you can use nl2br() to achieve the effect of line breaks on the page.
Method 1.

function chkstr($paravalue,$paratype) //Filter illegal characters
{
if($paratype==1)
{
$inputstr=str_replace("'","''",$paravalue);
}
elseif($paratype==2)
{
$inputstr=str_replace("'","",$paravalue);
}
return $inputstr;
}
$user1=chkstr($_GET["user"],1);
$user2=chkstr($_GET["user"],2);
//$user=$_GET["user"];
print "Method 1----------------
";
print "$user1
";
print "Method 2-----------------
";
print "$user2
";
?>
Method 2.


//Usage: qstr($str, get_magic_quotes_gpc())
function qstr($string, $magic_quotes=false, $tag=false)
{
$tag_str = '';
if ($tag) $tag_str = "'";
if (!$magic_quotes) {
If (strnatcmp(PHP_VERSION, '4.3.0') >= 0) {
Return $tag_str.mysql_real_escape_string($string).$tag_str;
}
$string = str_replace("'", "[url=file://\]\'[/url]" , str_replace('\', '\\', str_replace(" Return $tag_str.$string.$tag_str;
}
Return $tag_str.str_replace('\"', '"', $string).$tag_str;
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629753.htmlTechArticleIllegal character filtering This article mainly talks about PHP filtering illegal characters. It does not talk about the function of ASP filtering illegal characters, but the idea is the same. . ) filters characters that affect the normal operation of MySQL. When needed...
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
What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

PHP Dependency Injection: Boost Code MaintainabilityPHP Dependency Injection: Boost Code MaintainabilityMay 07, 2025 pm 02:37 PM

Dependency injection provides object dependencies through external injection in PHP, improving the maintainability and flexibility of the code. Its implementation methods include: 1. Constructor injection, 2. Set value injection, 3. Interface injection. Using dependency injection can decouple, improve testability and flexibility, but attention should be paid to the possibility of increasing complexity and performance overhead.

How to Implement Dependency Injection in PHPHow to Implement Dependency Injection in PHPMay 07, 2025 pm 02:33 PM

Implementing dependency injection (DI) in PHP can be done by manual injection or using DI containers. 1) Manual injection passes dependencies through constructors, such as the UserService class injecting Logger. 2) Use DI containers to automatically manage dependencies, such as the Container class to manage Logger and UserService. Implementing DI can improve code flexibility and testability, but you need to pay attention to traps such as overinjection and service locator anti-mode.

What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

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

Video Face Swap

Video Face Swap

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software