gpt4 book ai didi

php - 如何处理 preg-replace-callback 中的 eval 错误

转载 作者:行者123 更新时间:2023-12-03 08:44:14 25 4
gpt4 key购买 nike

我有一个 HTML 字符串 混合PHP 代码 .所以我只想对可能的代码进行评估并将其替换回去。我的想法是这样的:

$html='Hi it <b>PAPION</b>. Now timestamp is <?php echo time(); ?>. have a good time.';
$html = preg_replace_callback('/(<\?php)(.*?)(\?>)/ims',function($matches){
try {
ob_start();
eval($matches[2]);
return ob_get_clean();
} catch(Exception $e) {
return "";
}
}, $html);

它工作正常。

但是如果我的代码有错误,像这样:
$html='Hi it <b>PAPION</b>. Now timestamp is <?php echo xxtime(); ?>. have a good time.';
$html = preg_replace_callback('/(<\?php)(.*?)(\?>)/ims',function($matches){
try {
ob_start();
eval($matches[2]);
return ob_get_clean();
} catch(Exception $e) {
return "";
}
}, $html);

而不是只留下空白,它将使 $html 字符串空白。

PHP >5.4

有什么办法处理吗?

最好的祝福!

最佳答案

您在 catch 中将 $html 设置为 ""。必须更改您的代码,如下所示:

$html='Hi it <b>PAPION</b>. Now timestamp is <?php echo xxtime(); ?>. have a good time.';

preg_match('/(<\?php)(.*?)(\?>)/ims', $html, $matches);

$html = str_replace($matches[2], getEvalOutput($matches[2]), html);

echo "html is ".$html;

function getEvalOutput($matche){
try {
ob_start();
eval($matche);
return ob_get_clean();
} catch(Exception $e) {
return " ERROR happened";
}
}

你得到 fatal error ,你必须以某种方式处理它;这只是一个测试代码,供您了解方式:
<?php 

$phpCode = "
<?php
set_error_handler('myErrorHandler');
register_shutdown_function('fatalErrorShutdownHandler');
function myErrorHandler(\$code, \$message, \$file, \$line) {
echo \$message;
}
function fatalErrorShutdownHandler()
{
\$last_error = error_get_last();
if (\$last_error['type'] === E_ERROR) {
// fatal error
myErrorHandler(E_ERROR, \$last_error['message'], \$last_error['file'], \$last_error['line']);
}
}
\$html='Hi it <b>PAPION</b>. Now timestamp is <?php echo xxtime(); ?>. have a good time.';
\$html = preg_replace_callback('/(<\?php)(.*?)(\?>)/ims',function(\$matches){
try {
ob_start();
eval(\$matches[2]);
return ob_get_clean();
} catch(Exception \$e) {
}
}, \$html);
echo \$html;";

file_put_contents('a.php', $phpCode);
$x = exec( 'php a.php');
echo $x;
/* delete the file */
unlink('a.php');

关于php - 如何处理 preg-replace-callback 中的 eval 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58242171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com