Codeigniter file_put_contents:无法打开流:权限被拒绝



在服务器中上传图像时,我在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);````

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

可能是某些问题导致的:

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

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

// $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);

相关内容

  • 没有找到相关文章

最新更新