【问题标题】:Codeigniter file_put_contents: failed to open stream: Permission deniedCodeigniter file_put_contents:无法打开流:权限被拒绝
【发布时间】:2021-03-29 06:53:32
【问题描述】:

在服务器中上传图像时,我在 codeigniter 中遇到错误。但它在本地系统中运行良好。

遇到 PHP 错误:

Severity: Warning

Message: file_put_contents(upload/logo/1617000545.png): failed to open stream: Permission denied

Filename: models/Logo_m.php

行号:41

    list($type, $data) = explode(';', $data);
        list(, $data) = explode(',', $data);
       
        $data = base64_decode($data);
        $imageName = time().'.png';

        file_put_contents('upload/logo/'.$imageName, $data);````

【问题讨论】:

  • 我假设服务器是 linux 服务器?请检查upload/logo/ 目录是否存在于具有适当权限的服务器上。如果该目录已经存在,那么运行 CodeIgniter 应用程序的 webserver 用户可能没有该目录的写权限。
  • 它的窗口服务器。现在我懂了。由于权限问题。谢谢。

标签: php codeigniter


【解决方案1】:

您是否检查过您的目录或权限?

一些问题可能导致:

  1. 目录不存在,必须先创建。
  2. 权限/脚本没有足够的权限来写文件,你必须验证应用程序可以写目录并且目录是可写的。

您的代码也不会验证图像​​内容/元数据;

// $data = trim(explode(',', explode(';', $data)[1])[1]);
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
// determine absolute path
$imageDirectory = __DIR__ .'/upload/logo';
// check if string / content is an image
if (! ($imgInfo = getimagesizefromstring($data))) {
    // do exit here because data is not a binary image string
    throw new Exception('Data is not an image');
}
// check if image directory exist
if (!file_exists($imageDirectory)) {
    mkdir($imageDirectory, 755, true);
}
if (!is_dir($imageDirectory) || !is_writable($imageDirectory)) {
    throw new Exception('Could not save image. Directory is not writable.');
}

$extension = $imgInfo['mime'];
// optional to filter jpeg image
if ($extension  === 'jpeg') {
    $extension = 'jpg';
}
// use only time is not recommended due time is not unique, please change with random value
$baseName = time();
$imageName = $baseName . '.' . $extension;
$written   = file_put_contents($imageDirectory.'/'.$imageName, $data);

【讨论】:

  • 谢谢,这是因为该目录的权限错误。我解决了。
猜你喜欢
  • 2011-06-22
  • 2014-11-29
  • 1970-01-01
  • 2014-06-25
  • 2018-04-25
  • 2022-09-22
  • 2018-04-14
  • 1970-01-01
相关资源
最近更新 更多