PHP 7.4 absolute path - why is /.. ignored?

722 views Asked by At

I use this to include some file

require_once realpath(__DIR__) . '/../anotherfolder2/anotherfolder3/filename2.php

But for some reasons it seems that /.. is ignored and it triggers

Failed opening required '/var/domains/domain.com/foldername1/anotherfolder2/anotherfolder3/filename.php in /var/domains/domain.com/foldername1/anotherfolder2/filename1.php on line 10`

where realpath(DIR) = /var/domains/domain.com/foldername1

What could cause /.. to be ignored, is that something new in php 7.4?

2

There are 2 answers

1
Przemysław Niemiec On

Try to pass the whole path to realpath() function:

require_once realpath(__DIR__ . '/../anotherfolder2/anotherfolder3/filename2.php)

This function changes the dir1/dir2/../file1 into dir1/file1. In your case: /var/domains/domain.com/foldername1/../anotherfolder2/anotherfolder3/filename.php into /var/domains/domain.com/anotherfolder2/anotherfolder3/filename.php.

From documentation:

realpath() expands all symbolic links and resolves references to /./, /../ and extra / characters in the input path and returns the canonicalized absolute pathname.

https://www.php.net/manual/en/function.realpath.php

0
IMSoP On

I believe your statement that realpath(__DIR__) is '/var/domains/domain.com/foldername1' is incorrect.

Your error message includes the file path where the error happened:

... in /var/domains/domain.com/foldername1/anotherfolder2/filename1.php on line 10

So we know that __FILE__ will be '/var/domains/domain.com/foldername1/anotherfolder2/filename1.php', and __DIR__ will be '/var/domains/domain.com/foldername1/anotherfolder2'.

realpath is unlikely to change that, so we have:

require_once '/var/domains/domain.com/foldername1/anotherfolder2' . '/../anotherfolder2/anotherfolder3/filename2.php'

The .. will strip out the first anotherfolder2 giving:

require_once '/var/domains/domain.com/foldername1/anotherfolder2/anotherfolder3/filename2.php'

Which is the file path the error message says it can't find.