Home > php教程 > php手册 > 通过PHP自定义协议实现把字符串代码变为可以执行代码

通过PHP自定义协议实现把字符串代码变为可以执行代码

WBOY
Release: 2016-06-06 19:36:54
Original
1745 people have browsed it

以crossphp中解析注释配置为例,定义协议名:annotate $str_code = array(foo=bar); stream_register_wrapper(annotate,stringToPHPStream); $var=include(annotate://{$str_code}); print_r($var); 这样字符串$str_code就变成了一个php的array,远离eval吧,骚年

以crossphp中解析注释配置为例,定义协议名:annotate

$str_code = 'array("foo"=>"bar")';
stream_register_wrapper("annotate", "stringToPHPStream");
$var = include ("annotate://{$str_code}");

print_r($var);
这样字符串$str_code就变成了一个php的array, 远离eval吧,骚年~
如果要更改示例中协议名称,请更改stringToPHPStream这个类中的stream_open方法 CrossPHP
<?php

include __DIR__.'/stringToPHPStream.php';

$str_code = 'array("foo"=>"bar")';
stream_register_wrapper("annotate", "stringToPHPStream");
$var = include ("annotate://{$str_code}");

print_r($var);
Copy after login
<?php
/**
 * 字符串php代码通过wrapper转换为可以执行的php代码
 * <pre class="brush:php;toolbar:false">
 * 使用方式 stream_register_wrapper("自定义名字", "stringToPHPStream")
 * $var = include ("自定义名字://字符串代码")
 * 
Copy after login
* * @Auth: wonli * Class StringToPHPStream * @package Cross\Lib\Other */ class StringToPHPStream { /** * 代码内容 * * @var array */ static $content; /** * 在$content中的标示 * * @var string */ protected $key; /** * @var int */ protected $pos; /** * @param $path * @param $mode * @param $options * @param $opened_path * @return bool */ public function stream_open($path, $mode, $options, $opened_path) { $this->key = md5($path); if (! isset(self::$content[$this->key])) { self::$content[$this->key] = sprintf('pos = 0; return true; } /** * @param $count * @return string */ public function stream_read($count) { $content = self::$content[$this->key]; $ret = substr($content, $this->pos, $count); $this->pos += strlen($ret); return $ret; } /** * */ public function stream_stat() { } /** * */ public function stream_eof() { } }
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template