【问题标题】:WordPress: wp_filesystem->put_contents only writes last callWordPress:wp_filesystem->put_contents 只写最后一次调用
【发布时间】:2018-11-17 05:19:14
【问题描述】:

我有一个 WordPress 问题,想简单地将日志消息写入文本文件。我知道error_log 存在,但希望为不同的消息提供一个更加隔离的日志文件。

我正在使用wp_filesystem->put_contents,它确实写入文件并成功,但它只输出最后一次调用的数据

我有以下方法:

public static function log_message($msg) {
  error_log($msg);
  require_once(ABSPATH . 'wp-admin/includes/file.php');
  global $wp_filesystem;
  if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
      $creds = request_filesystem_credentials( site_url() );
      wp_filesystem($creds);
  }

  $bt = debug_backtrace();
  $caller = array_shift($bt);
  $logStr = date("Y-m-d hh:ii A",time())." - ".$caller['file'].":".$caller['line']." - ".$msg;
  $filePathStr = SRC_DIR.DIRECTORY_SEPARATOR.$logFileName;

  $success = $wp_filesystem->put_contents(
      $filePathStr,
      $logStr,
      FS_CHMOD_FILE // predefined mode settings for WP files
  );

  if(!$success) {
      error_log("Writing to file \"".$filePathStr."\" failed.");
  } else {
      error_log("Writing to file \"".$filePathStr."\" succeeded.");
  }
}

我称之为:

log_message("\nTest 1");
log_message("\nTest 2");
log_message("\nTest 3");

输出总是只有Test 3,而其他调用被忽略,它们的输出出现在 debug.log 以及所有成功消息中。

为什么会这样?

查看WPCodex的源代码,它在幕后使用fwrite。该文件在此代码中关闭,我不能使用任何“刷新”技术。

有没有办法解决这个问题?

【问题讨论】:

  • 根据this post , wp_filesystem 非常有限。您可能希望使用 PHP 的 fwrite 和文件句柄的 append 命令附加到文件。
  • 哦,有道理。我假设函数“file_put_contents”只是用于附加到文件......它将清除文件,并将内容放在那里。该函数用于计算/获取数据流,然后保存,不用于文件保存。

标签: php wordpress file fwrite file-put-contents


【解决方案1】:

我发现 WP_Filesystem 的来源使用了 file_put_contents (顾名思义),我认为这是为了附加到文件的数据。

这是不正确的。

此功能是取数据,然后将其写入文件,擦除之前的数据。 主要用于创建资源、下载文件等。

如果我想追加到一个文件,我需要使用'fwrite'。

post 对此进行了描述。

这是附加到文件的示例:

$filepath = '\path\to\file\';
$filename = 'out.log';
$fullpath = $filepath.$filename;

if(file_exists($fullpath)) {
  $file = fopen($filepath.$filename, "a");//a for append -- could use a+ to create the file if it doesn't exist
  $data = "test message";
  fwrite($file, "\n". $data);
  fclose($file);
} else {
  error_log("The file \'".$fullpath."\' does not exist.");
}

fopen docs 描述了此方法及其模式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多