Hi i recently faced this problem but was able to fix it. Actually spelling mistake in path. I want to know how to handle these error properly. i.e my program should continue executing and should safely return a false if mkdir fails. This is my code
try
{
foreach($folders as $folder)
{
$path = $path.'/'.$folder;
if(!file_exists($path))
{
if(!(mkdir($path)))
{
return false;
}
}
}
return true;
}
catch (Exception $e){
return false;
}
I just want if mkdir is not able to create it. It should return a false and the execution should continue
EDIT: Here is updated code based on community feedback. But still no proper answer to my question
if(!file_exists($newfolder))
{
if(mkdir($newfolder,0755,true))
{
return true;
}
}
Are you looking for setting the recursive flag to true?
<?php
// Desired folder structure
$structure = './depth1/depth2/depth3/';
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}
// ...
?>
The function appears to not be recursive. You will have to make the entire directory tree, down to your directory that you want to create.
Read here. Like sarnold said, just set the recursive argument to true.
Take a look at this sample, it might be what you are looking for.
http://www.php.net/manual/en/function.mkdir.php#92844
Related
I have a Laravel Controller Function file_fetch()
public function file_fetch(Request $request) {
$file = request('routename');
$destinationPath = public_path('/folder/'.$file);
if(!File::exists($destinationPath)){
$content = File::get($destinationPath);
return view('filefetch', compact('file','content'));
}
else {
return redirect('/')->witherrormessage('NO such File Exists');
}
}
This works if i check for file public/folder/app/index.html and if i check for public/newfolder (newfolder doesnt exist) and hence it executes else function and redirects with error message, but if i search for public/folder/app/ I havent specified the file name, but the directory exists, hence the if(!File::exists($destinationPath)) function is getting executed!
i want to check just and files inside the directory and even if the directory exists, if file is not present, throw a error message, saying file doesnt exists.
add one more additional condition to check given path is file but not a directory
public function file_fetch(Request $request) {
$file = request('routename');
$destinationPath = public_path('/folder/'.$file);
if(!File::exists($destinationPath) && !is_dir($destinationPath)){
$content = File::get($destinationPath);
return view('filefetch', compact('file','content'));
}
else {
return redirect('/')->witherrormessage('NO such File Exists');
}
}
You can probably fix your code by validating the routename input such that it will never be empty (and have a certain file extension maybe?)
, which is nice to do anyhow.
If that fails, you can try File::isDirectory($dir) which basically calls is_dir(...).
Note that it might give you more control on your storage solution if you use the Storage::disk('public') functionalities from Laravel. The API is a bit different but there's a wide range of probabilities associated with it. Read more about that here: https://laravel.com/docs/8.x/filesystem#introduction.
If you in different/multiple buckets.
//Do not forget to import
use Illuminate\Support\Facades\Storage;
if (Storage::disk('s3.bucketname')->exists("image1.png")) {
}
I'd like to know how to check if a text file is empty or not. It means that there is no text even some space, i.e. it was blank
function keyRemain($path)
{
$ambil = file_get_contents("data/$path/keywords.txt");
$kw = explode(",", $ambil);
if (count($kw) > 1) {
return false;
} else {
return true;
}
}
You have to check the empty function along with trim
function keyRemain($path)
{
$ambil = trim(file_get_contents("data/$path/keywords.txt"));
var_dump($ambil); // check the output here
if(!empty($ambil)) {
return false;
} else {
return true;
}
}
Maybe this was not the answer, just the another way to check the file. Before this was happend, the code appear instead the class. After i cut it and move it outside of the class it work perfectly without any errors.
file_get_contents() will read the whole file while filesize() uses stat() to detirmine the file size. Use filesize(), it should consume less disk I/O.
That's the answer found here, on stack...
You can also (on same link there's this answer):
clearstatcache();
if(filesize($path_to_your_file)) {
// your file is not empty
}
i have created one function to upload image using web services.
$image_url=time().$img_name;
$path=$_SERVER['DOCUMENT_ROOT'].'/img';
$image_url_src=$path."/".$image_url;
$current = file_get_contents($image_url_src);
$current = base64_decode($img_url);
$res=file_put_contents($image_url_src,$current);
chmod($image_url_src, 0777);
if($res===true)
{
$folder_img_url1="http://www.example.com/img/".$image_url;
$auth_error=array("img_url" => $folder_img_url1);
return json_encode($auth_error);
}
Everything is working properly.. only problem is why not returning value after this line of code file_put_contents($image_url_src,$current);
if i return any value before file_put_contents function than it works but after calling file_put_contents() after that not return works so why?
ANY HELP WOULD BE APPRECIATED
There is problem with permission of folder
First give permission
<?php
chmod($image_url_src, 0777);
if (file_put_contents($image_url_src,$current)!== false) {
{
$folder_img_url1="http://www.example.com/img/".$image_url;
$auth_error=array("img_url" => $folder_img_url1);
return json_encode($auth_error);
}
This function returns the number of bytes that were written to the
file, or FALSE on failure. Meaning: file_put_contents will never
return TRUE. It will return false however, so if you were insistent on
using a boolean value then you would need to use:
This Code is works for me...
$image_url=time().$img_name;
$path=$_SERVER['DOCUMENT_ROOT'].'/img';
$image_url_src=$path."/".$image_url;
//$current = file_get_contents($image_url_src); //this line of code is no need because of this not returning value..because it gives me an error.
$current = base64_decode($img_url);
$res=file_put_contents($image_url_src,$current);
//chmod($image_url_src, 0777); if will remove than also its works
if($res===true)
{
$folder_img_url1="http://www.example.com/img/".$image_url;
$auth_error=array("img_url" => $folder_img_url1);
return json_encode($auth_error);
}
Thank you for your time..
I have uploaded a lot of images from the website, and need to organize files in a better way.
Therefore, I decide to create a folder by months.
$month = date('Yd')
file_put_contents("upload/promotions/".$month."/".$image, $contents_data);
after I tried this one, I get error result.
Message: file_put_contents(upload/promotions/201211/ang232.png): failed to open stream: No such file or directory
If I tried to put only file in exist folder, it worked. However, it failed to create a new folder.
Is there a way to solve this problem?
file_put_contents() does not create the directory structure. Only the file.
You will need to add logic to your script to test if the month directory exists. If not, use mkdir() first.
if (!is_dir('upload/promotions/' . $month)) {
// dir doesn't exist, make it
mkdir('upload/promotions/' . $month);
}
file_put_contents('upload/promotions/' . $month . '/' . $image, $contents_data);
Update: mkdir() accepts a third parameter of $recursive which will create any missing directory structure. Might be useful if you need to create multiple directories.
Example with recursive and directory permissions set to 777:
mkdir('upload/promotions/' . $month, 0777, true);
modification of above answer to make it a bit more generic, (automatically detects and creates folder from arbitrary filename on system slashes)
ps previous answer is awesome
/**
* create file with content, and create folder structure if doesn't exist
* #param String $filepath
* #param String $message
*/
function forceFilePutContents ($filepath, $message){
try {
$isInFolder = preg_match("/^(.*)\/([^\/]+)$/", $filepath, $filepathMatches);
if($isInFolder) {
$folderName = $filepathMatches[1];
$fileName = $filepathMatches[2];
if (!is_dir($folderName)) {
mkdir($folderName, 0777, true);
}
}
file_put_contents($filepath, $message);
} catch (Exception $e) {
echo "ERR: error writing '$message' to '$filepath', ". $e->getMessage();
}
}
i have Been Working on the laravel Project With the Crud Generator and this Method is not Working
#aqm so i have created my own function
PHP Way
function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
{
$exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
array_pop($exploded);
$directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
if (!file_exists($directoryPathOnly))
{
mkdir($directoryPathOnly,0775,true);
}
file_put_contents($fullPathWithFileName, $fileContents);
}
LARAVEL WAY
Don't forget to add at top of the file
use Illuminate\Support\Facades\File;
function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
{
$exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
array_pop($exploded);
$directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
if (!File::exists($directoryPathOnly))
{
File::makeDirectory($directoryPathOnly,0775,true,false);
}
File::put($fullPathWithFileName,$fileContents);
}
I created an simpler answer from #Manojkiran.A and #Savageman. This function can be used as drop-in replacement for file_put_contents. It doesn't support context parameter but I think should be enough for most cases. I hope this helps some people. Happy coding! :)
function force_file_put_contents (string $pathWithFileName, mixed $data, int $flags = 0) {
$dirPathOnly = dirname($pathWithFileName);
if (!file_exists($dirPathOnly)) {
mkdir($dirPathOnly, 0775, true); // folder permission 0775
}
file_put_contents($pathWithFileName, $data, $flags);
}
Easy Laravel solution:
use Illuminate\Support\Facades\File;
// If the directory does not exist, it will be create
// Works recursively, with unlimited number of subdirectories
File::ensureDirectoryExists('my/super/directory');
// Write file content
File::put('my/super/directory/my-file.txt', 'this is file content');
I wrote a function you might like. It is called forceDir(). It basicaly checks whether the dir you want exists. If so, it does nothing. If not, it will create the directory. A reason to use this function, instead of just mkdir, is that this function can create nexted folders as well.. For example ('upload/promotions/januari/firstHalfOfTheMonth'). Just add the path to the desired dir_path.
function forceDir($dir){
if(!is_dir($dir)){
$dir_p = explode('/',$dir);
for($a = 1 ; $a <= count($dir_p) ; $a++){
#mkdir(implode('/',array_slice($dir_p,0,$a)));
}
}
}
I have folder, his name is "1", in this folder is 2 folders: "big_images" and "small_images"
I want delete folder "1" and his content, this is code:
function removeFullDir ($dir) {
$content = glob($dir."/*");
foreach ($content as $file) {
if (is_dir($file)) {
removeFullDir ($file);
}
else {
unlink($file);
}
}
rmdir($dir);
}
removeFullDir("1");
in localhost (XAMPP server, php version 5.4.4) this code works good. in remote server this code also works, but returns warning:
Warning: Invalid argument supplied for foreach()
in remote server, php version is 5.2.42
please tell me, why obtain I this warning?
This happens because glob does not return an array, which means that based on the documentation it must return false. This can happen when there is an error, but it can also happen when the directory happens to be empty:
Returns an array containing the matched files/directories, an empty
array if no file matched or FALSE on error.
Note: On some systems it is impossible to distinguish between empty match and an error.
To prevent the notice just guard against it:
function removeFullDir ($dir) {
$content = glob($dir."/*");
if(!$content) {
return;
}
// ...
}
One possible reason could be open_basedir restriction which means that glob() returns false and it will error at the foreach loop as $content is not an array, so you could check like:
//before foreach
if(is_array($content) && count($content) > 0) {