2015-12-05 45 views
0

我想用某種傳輸方式將函數發送到另一個腳本。如何從anonymus函數創建有效載荷

爲此,我需要在PHP可評估的有效載荷中打包此函數(將其評估爲另一個PHP文件中的字符串可能位於另一個服務器上)。

$abc = "testABC"; 
$xyz = new TestClass(); 
$test = true; 
$x = function() use ($test, $xyz, $abc) { 
    echo $abc; 
    var_dump($test, $xyz); 
}; 

此功能將被打包成一個字符串是這樣的:

$payload = function() { 
    $test = unserialize('b:1;'); 
    $xyz = unserialize('O:9:"TestClass":0:{}'); 
    $abc = unserialize('s:7:"testABC";'); 
    echo $abc; 
    var_dump($test, $xyz); 
}; 

回答

0

得到這個工作,我寫了下面的功能,翻出功能代碼,匹配任何use(...)條款和重命名變量它叫做。最後,它會將use(...)變量指定爲無法序列化的字符串。

function packAnonFunction($payload, ...$args) { 
    $func = new ReflectionFunction($payload); 
    $filename = $func->getFileName(); 
    $start_line = $func->getStartLine() - 1; 
    $end_line = $func->getEndLine(); 
    $length = $end_line - $start_line; 

    $source = file($filename); 
    $body = implode("", array_slice($source, $start_line, $length)); 
    $body = preg_replace('/(\$[a-z]+)\ \=\ function/', '\\$payload = function', $body); 
    if(preg_match('/use\s\((\$[a-zA-Z0-9]+(?:,\s\$[a-zA-Z0-9]+)*)\)/', $body, $matches)) { 
     $vars = $matches[1]; 
     if(strpos($vars, ', ') !== false) { 
      $parts = explode(', ', $vars); 
     } else { 
      $parts = [$vars]; 
     } 
     $return = []; 
     foreach($parts as $key => $variable) { 
      $return[$variable] = $args[$key]; 
     } 
     $variableString = ""; 
     foreach($return as $var => $value) { 
      $value = serialize($value); 
      $variableString .= "\t{$var} = unserialize('{$value}');\n"; 
     } 

     $body = str_replace(" use (" . $vars . ")", "", $body); 
     $body = str_replace("{\n", "{\n" . $variableString, $body); 
    } 
    return $body; 
} 

你可以只使用這樣的:

$abc = "testABC"; 
$xyz = new TestClass(); 
$test = true; 
$x = function() use ($test, $xyz, $abc) { 
    echo $abc; 
    var_dump($test, $xyz); 
}; 

echo packAnonFunction($x, $test, $xyz, $abc); 

唯一的滯後我是不是要解決的是,你得把ARGS($test, $xyz, $abc)以相同的順序因爲您分配了use(...)聲明。

看看它的實際操作:https://3v4l.org/89pXm

所以,你對此有何看法?