Str_replace replacement vulnerability in php functions
Definition and usage
The str_replace () function uses one string to replace other characters in the string.
Syntax
Str_replace (find, replace, string, count)
Parameter description
Find is required. Specifies the value to be searched.
Replace is required. Specifies the value to replace the value in find.
String is required. Specifies the string to be searched.
Count is optional. A variable that counts the number of replicas.
Tips and comments
Note: This function is case sensitive. Use str_ireplace () to perform a case-insensitive search.
Note: This function is binary secure.
Example 1
The code is as follows:
Echo str_replace ("world", "John", "Hello world! ");
?>
Output:
Hello John!
Example 2
In this example, we will demonstrate the str_replace () function with array and count variables:
The code is as follows:
$ Arr = array ("blue", "red", "green", "yellow ");
Print_r (str_replace ("red", "pink", $ arr, $ I ));
Echo "Replacements: $ I ";
?>
Output:
Array
(
[0] => blue
[1] => pink
[2] => green
[3] => yellow
)
Replacements: 1
Example 3
The code is as follows:
$ Find = array ("Hello", "world ");
$ Replace = array ("B ");
$ Arr = array ("Hello", "world ","! ");
Print_r (str_replace ($ find, $ replace, $ arr ));
?>
Output:
Array
(
[0] => B
[1] =>
[2] =>!
)
Vulnerability-related functions:
$ Arr1 = Array (
'Http: // img.jb51.net/img/offer/29/24/70/20/29247020 ',
'Http: // img.jb51.net/img/offer/29/24/70/20/29247020-1 ',
'Http: // img.jb51.net/img/offer/29/24/70/20/29247020-2'
);
$ Arr2 = Array (
'Http: // localhost/root/ups/af48056fc4.jpg ',
'Http: // localhost/root/ups/cf33240aa3.jpg ',
'Http: // localhost/root/ups/c30e40419b.jpg'
);
$ Data ='
';
$ Data = str_replace ($ arr1, $ arr2, $ data );
Var_dump ($ data );
?>
The result after replacement is:
String (169) "" The str_replace function declaration is probably like this: str_replace ($ search, $ replace, $ input [, & $ count]), for example, if you want to replace a string, $ input is the source string (called the data source ). this is unreasonable because it places the data source in 3rd bits, while str_pos, strtok, str_repeat and other functions place the data source in 1st bits. that is to say, str_replace does not replace the corresponding strings in the array. Instead, it replaces the first string in the array and then merges the same strings with the redundant strings.
Solution:
Function strrplace ($ arr1, $ arr2, $ data ){
If (is_array ($ arr1 )){
Foreach ($ arr1 as $ key => $ value ){
$ Data = str_replace_once ($ value, $ arr2 [$ key], $ data );
}}
Return $ data;
}
Function str_replace_once ($ needle, $ replace, $ data) // replace the first time
{
$ Pos = strpos ($ data, $ needle );
If ($ pos = false ){
Return $ data;
}
Return substr_replace ($ data, $ replace, $ pos, strlen ($ needle ));
}