【问题标题】:PHP file not copying correctly => file emptyPHP文件未正确复制=>文件为空
【发布时间】:2019-11-26 16:53:08
【问题描述】:

我目前正在尝试在 PHP 中将文件从位置 A 复制到 B。文件被复制,但它有 0 个字节。我很困惑为什么这个文件在这个过程之后是空的。这是我的代码:

if ( ! file_exists( $file_dir . $file_category ) ) {
    if ( ! mkdir( $file_dir . $file_category, 0777, true ) && ! is_dir( $file_dir . $file_category ) ) {
        throw new \RuntimeException( sprintf( 'Directory "%s" was not created', $file_dir . $file_category ) );
    }
    $data = '<html><body bgcolor="#FFFFFF"></body></html>';
    $file = fopen( $file_dir . $file_category . '/index.html', 'wb' );
    fwrite( $file, $data );
    fclose( $file );
    $data = 'deny from all';
    $file = fopen( $file_dir . $file_category . '/.htaccess', 'wb' );
    fwrite( $file, $data );
    fclose( $file );
}
copy( $output_dir . $filename, $file_dir . $file_category . '/' . $filename . '.pdf' );

任何帮助都会很棒。

【问题讨论】:

  • 如果您从$file_dir . $file_category 分配一个变量,事情会不会变得更简单,这样您就不必在每一行都重复该连接?

标签: php file directory


【解决方案1】:

只是我还是你在复制行中切换了源文件和目标文件:

copy( $output_dir . $filename, $file_dir . $file_category . '/' . $filename . '.pdf' );

PHP 文档说参数是这样的:

复制(字符串$source,字符串$dest[,资源$context]):bool

但您的第一个参数使用“$output_dir”(可能只是您的变量名)

如果不是这种情况,知道从哪里获得“$filename”会很有帮助,因为您没有在代码中的任何地方验证它,只有“$file_category”。您确定您的源文件确实存在并且有内容吗?

【讨论】:

  • $file_dir . $file_category 是他刚刚在代码顶部创建的目录,所以它可能是目的地。
  • @Barmar 你可能是对的。它只是让我感到困惑,他使用“file_exists”来测试文件夹是否存在。我会写评论,但我的代表不允许。
  • 是的,他应该使用is_dir()
  • 但是尽管有名字,file_exists() 将检查任何类型的目录条目,而不仅仅是文件。有单独的函数,如 is_fileis_dir 来检查类型。
  • 是的。我刚刚再次访问了 PHP 文档,我一定忘记了它也可以用于文件夹。只要我记得,我就一直使用“is_dir”。还要确保如果存在具有给定名称的文件,我不会得到误报
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
相关资源
最近更新 更多