Reputation: 113
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?
Upvotes: 11
Views: 85206
Reputation: 114
In MAMP on a Mac, something like this will work:
file_put_contents( '/Users/user/Sites/mysite.mamp/wp-content/test-files/delete-this-test.html', '<p>foo</p>' );
Upvotes: 0
Reputation: 11
Use FILE_USE_INCLUDE_PATH
If 'html' is the subfolder where you want to save the file to:
file_put_contents('html/'.$filename.'.ext', $text, FILE_USE_INCLUDE_PATH | FILE_APPEND | LOCK_EX);
Upvotes: 0
Reputation: 1
You must use backslashes:
file_put_contents('images\\'.$filename, base64_decode($imgBase64));
or
file_put_contents('K:\\Site\\images\\'.$filename, base64_decode($imgBase64));
Upvotes: -2
Reputation: 3577
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
.
Upvotes: 0
Reputation: 107
$dir = "folder_name".$filename;
you can use the above to simply put contents to any file of any folder.
Upvotes: 0
Reputation: 11
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..
Upvotes: 1
Reputation: 95101
Always use full paths and make sure the directory is writable. You can also use copy
directly with 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);
Upvotes: 17
Reputation: 20286
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_PATH instead of RELATIVE
Upvotes: 5
Reputation: 29424
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.
Upvotes: 11