Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save file with file_put_contents in folder

Tags:

php

apache

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?

like image 690
James Bedret Avatar asked Jun 20 '13 12:06

James Bedret


People also ask

How can save file in specific folder in PHP?

php $target_Path = "images/"; $target_Path = $target_Path. basename( $_FILES['userFile']['name'] ); move_uploaded_file( $_FILES['userFile']['tmp_name'], $target_Path ); ?> when the file(image) is saved at the specified path... WHAT if i want to save the file with some desired name....

Does file_ put_ contents create file?

The file_put_contents() function checks for the file in which the user wants to write and if the file doesn't exist, it creates a new file.

How do I save a file in PHP?

PHP code: saving a file with fopen / fwrite 'myfile1. txt'; $fp = fopen($file, "w") or die("Couldn't open $file for writing!"); fwrite($fp, $data) or die("Couldn't write values to file!"); fclose($fp); echo "Saved to $file successfully!"; ?>

What is file put content?

The file_put_contents() function writes a string to a file. The function returns the number of bytes that were written to the file, or FALSE on failure.


2 Answers

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);
like image 190
Baba Avatar answered Oct 08 '22 01:10

Baba


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

like image 44
Robert Avatar answered Oct 08 '22 02:10

Robert