【问题标题】:What is best way to use file_put_contents to write PHP code to file?使用 file_put_contents 将 PHP 代码写入文件的最佳方法是什么?
【发布时间】:2014-02-13 09:32:12
【问题描述】:

这是脚本:

<?php 

$line0PHP = '<?php';
$line1PHP = 'defined( '_JEXEC' ) or die( 'Restricted access' );';
$line2PHP = 'jimport( 'joomla.plugin.plugin');';
$line3PHP = 'jimport( 'joomla.html.parameter');';
$line4PHP = 'class&#32;plgSystem'.$titleString.'plugin&#32;extends&#32;JPlugin';
$line5PHP = '{';
$line6PHP = 'function plgSystem'.$titleString.'plugin()';
$line7PHP = '{';
$line8PHP = '}';      
$line9PHP = '}';
$line10PHP = '?>';

$phpFileOutput = $line0PHP.'&nbsp;'.$line1PHP.'&nbsp;'.$line2PHP.'&nbsp;'.$line3PHP.'&nbsp;'.$line4PHP.'&nbsp;'.$line5PHP.'&nbsp;'.$line6PHP.'&nbsp;'.$line7PHP.'&nbsp;'.$line8PHP.'&nbsp;'.$line9PHP.'&nbsp;'.$line10PHP;

$varOutputPhp = print_r($phpFileOutput, true);

file_put_contents($root,$varOutputPhp);

?>

$root$titleString 是前面定义的。

【问题讨论】:

  • 当心,您的代码中有一些“智能引号”。 PHP 只支持普通的单引号和双引号。
  • 在写入文件之前考虑heredoc 字符串和htmlspecialchars
  • HTML 实体由浏览器处理,而不是 PHP。您应该将真实字符写入文件。
  • 正如 Barmar 所说,那些智能/弯引号会立即引发错误。改为$title = 'titleValue';
  • titleValue 已更新。我刚刚从文字处理器中提取出来。代码中没有这种方式。

标签: php file overwrite htmlspecialchars


【解决方案1】:

你有引用问题,因为你的单引号字符串中有单引号。您需要转义它们,或使用双引号。而且您仍然有许多 HTML 实体需要用普通字符替换。

<?php 

$line0PHP = '<?php';
$line1PHP = "defined( '_JEXEC' ) or die( 'Restricted access' );";
$line2PHP = "jimport( 'joomla.plugin.plugin');";
$line3PHP = "jimport( 'joomla.html.parameter');";
$line4PHP = 'class plgSystem'.$titleString.'plugin extends JPlugin';
$line5PHP = '{';
$line6PHP = 'function plgSystem'.$titleString.'plugin()';
$line7PHP = '{';
$line8PHP = '}';      
$line9PHP = '}';
$line10PHP = '?>';
$phpFileOutput = $line0PHP.' '.$line1PHP.' '.$line2PHP.' '.$line3PHP.' '.$line4PHP.' '.$line5PHP.' '.$line6PHP.' '.$line7PHP.' '.$line8PHP.' '.$line9PHP.' '.$line10PHP;

【讨论】:

  • 感谢@Barmar,解决了问题。
【解决方案2】:

这是编写代码的正确方法: file_put_contents($filename, $newfilecode);

【讨论】:

  • 这有什么帮助?只是变量名不同而已。
【解决方案3】:
    $text = "<?php \n";
    $text .= "defined('_JEXEC') or die( 'Restricted access' );\n";
    $text .= "jimport( 'joomla.plugin.plugin');\n";
    $text .= "jimport( 'joomla.html.parameter');\n";
    $text .= "class plgSystem".$titleStringplugin." extends JPlugin\n";
    $text .= "{\n";
    $text .= "function plgSystem".$titleString."plugin()\n";
    $text .= "{\n";
    $text .= "}\n";
    $text .= "}\n";
    $text .= "?>\n";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    相关资源
    最近更新 更多