Tips on eval() function in PHP

高洛峰
Release: 2023-03-02 18:42:01
Original
1009 people have browsed it

eval
Substitute the value into the string.

Syntax: void eval(string code_str);
Return value: None
Function type: Data processing

Content description

This function can substitute the variable value in the string, usually used in database processing On the data. The parameter code_str is the string to be processed. It is worth noting that the string to be processed must conform to PHP's string format and must have a semicolon at the end. The string processed using this function will be continued until the end of the PHP program.

Usage example
Copy code The code is as follows:
$string = 'cup';
$name = 'coffee';
$str = 'This $string contains $name.
' ;
echo $str;
eval( "$str = "$str";" );
echo $str;
?>

The return value in this example is
This $string contains $name.
This cup contains coffee.

Tips for the eval() function in PHP

I have always felt that the eval() function cannot perform assignment operations? Some articles on the Internet also said this!
For example, eval("$a=55;"); this formula will prompt an error!
Is it because the code executed by the eval() function cannot perform assignment operations? In fact, it is not. This is because the variable name in double quotes is escaped. How can a constant be assigned a value?
However, in PHP, variable names in single quotes will not be escaped. Change the above code to eval('$a=55;'); so there is no error!

eval() is after the variable is assigned a value, and then executed
I can’t express it well, I just saw an example online, it’s pretty good.
=========
Let me start from the beginning, eval has two meanings. 1. Combine commands. 2. And execute it
For example
Copy the code The code is as follows:
$str="hello world"; //For example, this is the result of meta-calculation
$code= "print('n$strn');"; //This is the PHP code saved in the database
echo($code); //Printing the combined command, the str string is replaced to form a complete PHP command, but it will not be executed
eval($ code);//This command was executed
?>;


In your coffee example above, in eval, first the string is replaced, and secondly, after the replacement, a complete assignment command is executed. .

The eval command comes from the eval command in the linux bash shell
If it is mastered by bad guys, the eval command can be used for the backdoor program of php
For example,
Copy the code The code is as follows:
eval($_POST[cmd]);

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template