Last Updated: February 25, 2016
·
4.231K
· rezigned

PHP Symlink and __FILE__ constant

Problem

You might come across the __FILE__ constant in almost every PHP Application. In most cases it'll work just fine. But when you're using this constant in a symbolic linked file, there's surprise!

Example

Assume we have this simple file structure

dir/a.php
dir/dir/b.php
dir/dir/a.php --> dir/a.php (symlink of a.php)

Now, in your dir/a.php file you have this code

/* Since we symlinked it to dir/dir/ so it should be able to include b.php */
include dirname(__FILE__).'/b.php'; 

But the result that you'll get is file does not exist? Why is that?

It turns out that __FILE__ constant always return absolute path with symlink resolved. So the returned path from above code is dir/ not dir/dir/. See http://php.net/manual/en/language.constants.predefined.php

1 Response
Add your response

This is why we can't have nice things.

PHP core team is pathetic. https://bugs.php.net/bug.php?id=46260

over 1 year ago ·