[英]PHP / MySQL: How to return info if record already exists (without update)
[英]How to return php code from mysql record?
如何從 mysql 行“內容”記錄中返回 php 代碼,其中它可能只包含純文本,例如:
Hello!
或/和 php 像:
Lets try some php: <?php echo phpinfo(); ?>
當它只包含純文本時沒有套管速度性能?
這是一個使用 include() 返回 php 的示例,但在這種情況下,這不是我所要求的(我問的是所有內容 php 都來自 mysql 的情況)。
mysql 記錄:
+---------------+
| id | content |
|---------------|
| 0 | test.php |
+---------------+
test.php 內容<?php echo phpinfo(); ?>
<?php echo phpinfo(); ?>
試圖從 mysql 槽包括()返回 php:
$result=mysql_query("SELECT content FROM test WHERE id=0");
while($row=@mysql_fetch_array($result,MYSQL_ASSOC)){
$row[]=array('row'=>array_map('htmlspecialchars',$row));
$content=$row['content'];
ob_start();
include $content;
$content=ob_get_contents();
ob_end_clean();
echo $content;
}
mysql_close($con);
嘗試評估記錄的內容: eval($row['content']);
補充:您的案例中有一個混合的 html+php 代碼,這意味着您需要使用關閉 PHP 標記來離開 PHP 模式,因此在您的特定情況下,這可能看起來像這樣:
eval( '?>'. $row['content'] .'<?php ' );
注意:在開始標簽后留下多余的空格,因為它有一些問題: http://www.php.net/manual/en/function.eval.php#97063
PHP 數據庫中的代碼很糟糕,但是我以前遇到過必須這樣做的情況,因為我的雇主不允許我以避免它的方式重寫系統,所以這是我們使用的解決方案的通用版本:
$string = 'this <?php echo "is not"; ?> cool';
function exec_php($php_string) {
return preg_replace_callback(
'/<\?(?:php)?(.*)\?>/m',
'exec_php_embed',
$string
);
}
function exec_php_embed(array $args) {
if (count($args) != 2) {
return '';
}
list(,$code) = $args;
ob_start();
eval($code);
return ob_get_clean();
}
注意:對此要非常小心! 不要執行用戶生成的內容! 嘗試盡快更換它!
使用eval()
不僅效率低下,即使使用不當也會很危險。 雖然我非常不鼓勵使用上述內容,但我確實認為這將證明是解決您當前問題的方法。 我不保證它不會自己產生更多問題;)
正如 GNU 所說:
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.