Problem checking if there is a directory with PHP

2

I'm trying to check if a directory exists and if not create it, but the page does not work for me when I use the functions "file_exists" or "is_dir".

I've tried it this way:

 if(!file_exists( $path )
        mkdir($path);

And so:

if(!is_dir ( $path )
    mkdir( $path );

And I've also tried to use the path with different formats:

According to the documentation, if I'm on windows, I should do it like this:

$path= "C://Apache24/htdocs/uploads/carpeta"

Although I have also tried to do so

$path ="C:/Apache24/htdocs/uploads/carpeta"

And so

$path= "./uploads/carpeta"

Even so:

$path= $_SERVER['DOCUMENT_ROOT']."/uploads/carpeta"

In all cases it fails me. In the local I'm working on Windows but I suppose that when I upload it to the hosting it has to run on Linux.

Does anyone know why these functions fail or how to fix it?

    
asked by Iván Rodríguez 06.10.2018 в 20:00
source

1 answer

3

The ! file_exists code is correct. You should only keep in mind that a parenthesis is missing and add the keys to make it clearer but not necessary.

if(!file_exists( 'images/pics/' )) {
   echo "no existe";
}

And I also think that you have a difference with $ path. It is important to understand how that works. $ path refers to the place where you run the file_exists function. For example if you are in

  

C: \ xampp \ htdocs \ delete \

and you want to validate if the directory exists

  

C: \ xampp \ htdocs \ delete \ images \ pics

$ path should be images / pics (note changed bars and the path relative to where the function is executed). If on the contrary you will execute the function from

  

C: \ xampp \ htdocs \ delete \ tmp

then $ path should be ../ images / pics , that is, download a directory (../) and then the path to validate (images / pics).

Hopefully this information will be useful.

    
answered by 06.10.2018 / 22:37
source