Create a directory when the file with that name exists

61 Views Asked by At

I have a function for my code editor project that takes some long path and creates appropriate directory or file with it example :

create_file( '/home/me/' , 'dir/file.txt' ) this creates a file called file.txt along with dir directory if not existing.

The problem is that the function gives an error saying Warning: mkdir(): File exists when I am making a directory called home/me/dir

( there is file called /home/me/dir )

here's the function

isn't there a way to make the directory with same name?

function create_file(string $path , string $filename) :bool {
    
            $return = false;
    
            $full_path = '/' . $path .'/'.$filename;
            
            if( !file_exists($full_path) && $this::is_within_allowed_path($path) && $this->is_allowed('/'.$path) && in_array( 'c' , $this->permissions('/'.$path) )) {
    
                $path = realpath('/'.$path);
                $parts = explode('/', trim($filename) );
                $fileName = array_pop($parts);
    
                $dir_to_make = '/' . $path .'/' . implode( '/' , array_filter( $parts ) );
                
                if( !is_dir( $dir_to_make ) ) mkdir( $dir_to_make , 0777 , true );
    
                if( trim($fileName) !== '' ) file_put_contents( $dir_to_make . '/' . $fileName , '' );
                
                $return = true;
    
            }
    
    
            return $return;
        }

I know I can do file_exists() but that won't solve anything

1

There are 1 best solutions below

1
Benny On

Lets take it by steps.

  1. The name already exists in the same directory.
  2. It appears that the conflicting file does not have an extension

So I suggest this algo

  1. if file exist rename by adding extension or something
  2. Create your directory