How to make file_exists search in the correct folder?

Asked

Viewed 43 times

0

I’m testing if a file exists like this:

if (file_exists('assets/img/items/'. $currentLocation['id'] .'c.jpg')){
    $galleryItem .= '<img src="assets/img/items/'. $currentLocation['id'] .'c.jpg" alt="">';
}

The issue is that the PHP file that is doing this query is on assets/external/ so he can’t find the file.

How to make it look in the right folder?

Hugs.

  • 1

    You can use .. to return a directory, the path would be ../img/items/

  • @Denisrudneidesouza worked

1 answer

1


The comment of @Denis Rudnei de Souza is correct. However you can add a little more precision (avoid that in multiple file inclusions, the current directory accidentally changes) using the constant __DIR__ and the function realpath().

The constant DIR will return the currently running script directory and the function realpath() will transform relative paths (../pasta1/../a.php) into absolute paths.

So applying to your situation becomes:

$caminho = 'assets/img/items/'. $currentLocation['id'] .'c.jpg';
if (file_exists(realpath(__DIR__ . '/../' . $caminho))){

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.