【问题标题】:php- Output directory does not existphp-输出目录不存在
【发布时间】:2019-03-11 12:00:18
【问题描述】:

我正在尝试将新文件保存到我的 Symfony 项目中的初始目录,但无论我尝试过什么都会抛出:

输出目录不存在

我确定该路径存在,希望在其中创建一个 .txt 文件!

$path = "/var/www/app/web/uploads/my-file.txt";
$file = basename($path);

$txt = new File();
$txt->setSavePath($file);
$txt->save();

和:

public function setSavePath($savePath)
{
    if (!is_dir($savePath)) {
        throw \Exception("Output directory does not exist");
    }

    // Add trailing directory separator the save path
    if (substr($savePath, -1) != DIRECTORY_SEPARATOR) {
        $savePath .= DIRECTORY_SEPARATOR;
    }

    $this->savePath = $savePath;
}

【问题讨论】:

  • 您确定大小写相同(大写与小写) Linux 区分大小写。还要确保 PHP 系统用户有权访问这些文件夹。它们可以存在并由 root 拥有,并且没有 PHP 访问它们的权限,那么他就不会看到它们。
  • 不应该setSavePath() 获取完整路径而不仅仅是文件名吗?现在,您只是传递文件名(没有路径,因为您使用了basename())。然后,在该方法中,您正在检查是否存在与文件同名的文件夹。如果没有,则输出“输出目录不存在”。我很确定这不是你的本意,对吧?
  • 试过了!错误是一样的。 @MagnusEriksson
  • 你是只传递了路径,还是传递了完整的字符串(包括文件名)?查看代码,它应该获取没有文件名的路径,否则您将再次遇到相同的问题(因为它会检查文件名是否为文件夹)。
  • 显然该目录不存在或您打错了。回显$file 的结果并尝试查看是否可以手动到达该路径。你也可以试试/ vs ` \ `

标签: php directory save file-put-contents


【解决方案1】:

使用dirname 代替basename

因为

$path = "/var/www/app/web/uploads/my-file.txt";
$file = basename($path);
// $file is `my-file.txt` and not the path `/var/www/app/web/uploads` you expect

【讨论】:

    【解决方案2】:

    您正在检查 $savePath 是否是一个目录 is_dir,您正在传递一个文件路径,因为您的异常被抛出。

    你应该检查 $savePath 是一个目录并且它是可写的。

    public function setSavePath($savePath)
    {
        if (!is_writable(dirname($savePath))) {
            throw \Exception("Output directory does not exist or not writable.");
        }
    
       //... rest of code.
    }
    
    

    参考:http://php.net/is_dir
    参考:http://php.net/is_writable

    【讨论】:

      猜你喜欢
      • 2011-12-19
      • 2011-08-07
      • 2021-01-12
      • 2018-02-02
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多