php 将文件与file_put_contents一起保存在文件夹中

ijxebb2r  于 2023-01-16  发布在  PHP
关注(0)|答案(8)|浏览(213)
file_put_contents('image.jpg',file_get_contents('http://static.adzerk.net/Advertisers/12f0cc69cd9742faa9c8ee0f7b0d210e.jpg'));

将文件保存在当前文件夹中工作正常,但如果我尝试

file_put_contents('/subfolder/image.jpg',file_get_contents('http://static.adzerk.net/Advertisers/12f0cc69cd9742faa9c8ee0f7b0d210e.jpg'));

我有一个错误:
无法打开流:[...]中没有这样的文件或目录
为什么会出现此错误?如何将文件保存到子文件夹中?

n3schb8v

n3schb8v1#

始终使用完整路径并确保目录可写。您也可以直接使用copy和URL

$url = 'http://static.adzerk.net/Advertisers/12f0cc69cd9742faa9c8ee0f7b0d210e.jpg';
$dir = __DIR__ . "/subfolder"; // Full Path
$name = 'image.jpg';

is_dir($dir) || @mkdir($dir) || die("Can't Create folder");
copy($url, $dir . DIRECTORY_SEPARATOR . $name);
toe95027

toe950272#

尝试省略第一个斜杠:

file_put_contents('subfolder/image.jpg',file_get_contents('http://static.adzerk.net/Advertisers/12f0cc69cd9742faa9c8ee0f7b0d210e.jpg'));

如果仍然不起作用,请检查访问权限。

2eafrhcq

2eafrhcq3#

您应该检查文件夹是否存在,如果不存在,请创建此文件夹

$dir_to_save = "/subfolder/";
if (!is_dir($dir_to_save)) {
  mkdir($dir_to_save);
}
file_put_contents($dir_to_save.'image.jpg',file_get_contents('http://static.adzerk.net/Advertisers/12f0cc69cd9742faa9c8ee0f7b0d210e.jpg'));

还要确保要使用ABSOLUTE_PATH而不是RELATIVE

oyxsuwqo

oyxsuwqo4#

file_put_contents('../subfolder/image.jpg',file_get_contents('http://static.adzerk.net/Advertisers/12f0cc69cd9742faa9c8ee0f7b0d210e.jpg'));

add "../" in your string put into the file_put_contents function then it will work fine..
lxkprmvk

lxkprmvk5#

$dir = "folder_name".$filename;

你可以使用上面的简单地把内容到任何文件夹的任何文件.

rta7y2nd

rta7y2nd6#

我的问题是由文件夹权限引起的.当我创建我的子文件夹时,root是所有者,因为我的php是以apache用户运行的,我需要更新文件夹的所有者为apache .

ybzsozfc

ybzsozfc7#

使用文件使用包含路径
如果“html”是要保存文件的子文件夹:
文件放入内容('html/'.$文件名。'. ext',$文本,文件使用包含路径|文件_附加|锁定_EX);

6qqygrtg

6qqygrtg8#

必须使用反斜杠:

file_put_contents('images\\'.$filename, base64_decode($imgBase64));

file_put_contents('K:\\Site\\images\\'.$filename, base64_decode($imgBase64));

相关问题