How to execute a string of PHP code

Source: Internet
Author: User
Tags fread php cli

Ext.: https://www.cnblogs.com/dormscript/p/6163774.html

How to execute a string of PHP code

Recently, as a result of the project, an issue has been raised: How to execute a string of PHP code (PHP and HTML mix).
Note: Traditionally, PHP code is stored in a file and can be run directly. The following discussion is about how to run a PHP code if it is obtained from a database.

The most intuitive solution
    • Write the string code to a temporary file, include the file in the project, and then delete the temporary file by completing the execution.
    • Systems functions such as system exec
    • PHP function eval (will there be any security issues?)
A further blind thought
    • The string code as a parameter, passed into the PHP CLI or php-fpm run
    • Redefine include so that include can manipulate strings directly
Verification of several ideas
    • 1: Write temporary files, then include files. Hao no doubt, feasible. So not every time you have to write files, each request to write a file. OK, there is always a way to solve, cache + expiration verification and the like, but always feel that this program is not professional.

    • Functions such as 2:system exec. Think about it a little bit and you'll understand that this kind of function is executing system commands, not running PHP code

    • The 3:eval function, written in the manual, reads:

      Caution:the eval () language construct is very dangerous because it allows execution of arbitrary PHP code. Thus is discouraged. If you had carefully verified that there was no other option than to use this construct, pay special attention don't to pass Any user provided data into it without properly validating it beforehand.

    • 4:PHP-FPM CLI mode is there a way to solve this kind of problem
      The initial idea is to pass the string code to FPM, CLI mode, and wait for the result to be returned.
      But there is a mishap, the string code that needs to be executed is contextual. For example, a variable $_get is used in the string code, and if the string code is passed to FPM, and the $_get variable is not passed through, the code is not functioning properly.

    • 5:include can I manipulate the string directly?
      Well, the previous 4 methods seem to be not satisfied, then dig this idea deep

* * First, what is the principle of include in PHP? **
Did not go to see the source, guess it, 1: Read the file (Fopen,fread and the like) 2: Parsing PHP Syntax 3: Run the Code

* * So, if you can get fopen,fread to manipulate strings, maybe this problem is solved? **
Imagine: Converting a string to an object or stream, providing a fopen,fread interface. First think of the PHP SPL should have such interfaces, check the official PHP manual, find the PHP manual on the "Supported Protocols and Encapsulation Protocol" section (colleagues also mentioned the use of custom protocols), the following is the test of the simplest demo: (Encapsulating the custom protocol, using include direct manipulation of the string)

<?PHP//business needs: PHP code that reads strings from a databasefunctionMysql_get ($id) {return' <?php $i = '.$id.‘echo "Contextvalue:" $contextName. " \ n "; echo" Hello $i \ n "; ‘;}//Custom ProtocolsclassVariablestream {Private $string;Private $position; Public functionStream_open ($path,$mode,$options, &$opened _path) {$url=Parse_url($path);$id=$url["Host"];//Remove PHP string code from ID to database$this-string= Mysql_get ($id);$this->position = 0;return true;} Public functionStream_read ($count) {$ret=substr($this-string,$this->position,$count);$this->position + =strlen($ret);return $ret;} Public functionstream_eof () {} Public functionStream_stat () {}}Stream_wrapper_register("Var", "Variablestream");//Context Variables$contextName= "1000";//include string PHP code. (PHP code is read from the database, where 199 is the primary key ID of the database)include("var://199");//Modifying context variables$contextName= "2000";//introduce another string of PHP codeinclude("var://299");

OK, finally found a solution to the idea. Continue to think, since we want the final display to include this way, the inside of the include is a system function such as fopen, then fopen in addition to support the custom protocol, but also what support?
Manual, Fopen's first parameter $filename, can be a file name, or it can be "scheme://..." Format, the second format is the custom protocol method described above. Continue to see the relevant things, found Splfileinfo, stream_context_create, but does not solve the problem.

Summarize

Now there are 3 ways to do this, which is better.
1: Write temporary files, add cache, direct include
2:eval, the Official handbook says there's a security problem with this function.
3: Custom protocol, direct include

First Exclude Method 1, cause 1: The cache file will increase the hard disk I/O. Reason 2: Not professional (this is not a small problem)
As for the safety issue that is mentioned in Eval, after reading the passage in the manual, I find that he is only suggesting that you are now running code other than the project code, so be careful. In this view, Method 2 is not more dangerous than Method 3.

Select the standard, if only a small feature in the project needs to execute PHP string, then use eval directly
If you have a large number of such requirements in your project, it is convenient to encapsulate a custom protocol. The references in the project are as follows: include ("Protocolname://param");

Well, most of the above offers are ideas, hope that the idea is useful to you

How to execute a string of PHP code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.