PHP scripts using __FILE__ break when they are moved

View Comments
magic constants in the php manual

The __FILE__ magic constant contains the full path to the PHP script that it is being used in. The path used is local, not remote. Local paths are meant to be used when dealing with other files in the file system, such as when using the include, include_once, require, and require_once directives, and when opening, editing, and saving files on the server. Since the path on every server is going to be different, and since it’s a value that you expect the average user to be unaware of, using the __FILE__ magic constant allows an application to learn the path without requiring the user to learn it, first. But, once a file using the __FILE__ magic constant is moved, difficulties arise.

What happens when the file is moved?

A common misconception of PHP is that it is an interpreted language. This misconception comes from the fact that PHP programmers do not have a manually compile any PHP scripts. Previously, PHP was an interpreted language, but in one of the PHP 4 versions on into PHP 5, it became a compiled language. As an interpreted language, it simply was not fast enough. PHP programmers do not have to use a compiler because it’d be too much of a change from PHP 3 to PHP 4 if they were required to do so. So, after a file is created or edited, that file is compiled when it is first run.

Files are only recompiled after they are edited. When a file is moved, it is not recreated. It is only relocated. This means that anything that is determined at compile-time remains the same. While this makes sense for most things, it does not make sense for the one thing that has changed when a file is relocate: the __FILE__ magic constant (and, in PHP 5.3.0 and above, the __DIR__ magic constant). Magic constants are determined at compile time. For the rest of the magic constants, this makes perfect sense since they only change if the file has been changed. So, how do we handle this?

Forcing the __FILE__ magic constant to update

If you are getting errors when your files try to include other files, but the paths that they are trying to include them from is their old paths, chances are that you are facing this issue. By design, PHP will not recompile your script just because it has been moved to a different folder. The whole purpose of compiling the file when it is updated is to avoid having to recompile it. So, the solution to our issue is to force PHP to recompile the file. The solution is simple.

In order to force PHP to recompile a file, simply update it. Locally, this can be done by re-saving the file (or, in some programs, adding a character, deleting it, and then saving it). Remotely, this can be done by re-uploading the file (or, if you do not have the file locally, downloading it, then re-uploading it).

Problem solved.

Did you like this? Share it:
blog comments powered by Disqus