php 使用 file_put_contents 在文件夹中保存文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17213403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save file with file_put_contents in folder
提问by James Bedret
file_put_contents('image.jpg',file_get_contents('http://static.adzerk.net/Advertisers/12f0cc69cd9742faa9c8ee0f7b0d210e.jpg'));
Saving the file in current folder is working ok, but if I try
将文件保存在当前文件夹中可以正常工作,但是如果我尝试
file_put_contents('/subfolder/image.jpg',file_get_contents('http://static.adzerk.net/Advertisers/12f0cc69cd9742faa9c8ee0f7b0d210e.jpg'));
I have an error:
我有一个错误:
failed to open stream: No such file or directory in […]
无法打开流:[...] 中没有这样的文件或目录
Why does this error occur? How can I save the file in a subfolder?
为什么会出现这个错误?如何将文件保存在子文件夹中?
回答by Baba
Always use full paths and make sure the directory is writable. You can also use copy
directly with URL
始终使用完整路径并确保目录可写。您也可以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);
回答by ComFreek
Try to leave out the first slash:
尝试省略第一个斜杠:
file_put_contents('subfolder/image.jpg',file_get_contents('http://static.adzerk.net/Advertisers/12f0cc69cd9742faa9c8ee0f7b0d210e.jpg'));
Check the access rights if this still doesn't work.
如果这仍然不起作用,请检查访问权限。
回答by Robert
You should check if folder exsits and if not create this folder
您应该检查文件夹是否存在,如果不存在则创建此文件夹
$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'));
also make sure that you want to use ABSOLUTE_PATHinstead of RELATIVE
还要确保您要使用ABSOLUTE_PATH而不是RELATIVE
回答by Satvindar Singh
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..
回答by Devanshu Goyal
$dir = "folder_name".$filename;
you can use the above to simply put contents to any file of any folder.
您可以使用上述内容简单地将内容放入任何文件夹的任何文件中。
回答by Sean Bradley
my problem was caused by folder permissions.
when I created my subfolder, the root
was the owner,
since my php runs with the apache
user, I needed to update the owner of the folder to be apache
.
我的问题是由文件夹权限引起的。当我创建我的子文件夹时,它root
是所有者,因为我的 php 与apache
用户一起运行,我需要将文件夹的所有者更新为apache
.
回答by Rom Sed
You must use backslashes:
您必须使用反斜杠:
file_put_contents('images\'.$filename, base64_decode($imgBase64));
or
或者
file_put_contents('K:\Site\images\'.$filename, base64_decode($imgBase64));