user3420034 user3420034 - 1 month ago 23
PHP Question

Configure PHPStorm to take into account relative paths for included files?

I've just started with PHPStorm and I'm encountering an issue.

So when including a file, if you then include another file within that the path isn't understood correctly.

e.g.
Folder structure:

root/ Contains index.php
view/ Contains view.php
lib/ Contains functions.php


So if I include view.php in index.php:

index.php:

include('view/view.php');
or
require('view/view.php');


When this code is run, anything within view.php is included in index.php, so any files included in view.php are relative to the root directory.

view.php:

include('lib/functions.php');


But PHPStorm thinks they're relative to the view directory.

view.php:

include('../lib/functions.php');


Which in this situation they aren't.

This issue is also occurring for things like:
<a href="index.php">Link</a>


How do I configure PHPStorm to pick up this situation? I'd assumed it would work this out automatically, but currently it isn't.

Specific example:

private/
privatefile.php
public/
index.php
views/view1.php //Included in index.php
views/view2.php //Included in index.php


Would 'public' be the resource root in this situation if I want to include privatefile.php in view1.php?

So the include in view1.php would look like: include(
'../private/privatefile.php'
);

Answer

Marking folder as "Resources root" will only help for HTML/CSS (e.g. links to images/css files/js files and alike) -- it will NOT affect actual PHP includes in any way.

In your public/index.php (which is your entry-point script -- all requests will go trough it) define some constants, e.g.

define('DIR_WEB', __DIR__); // points to your public
define('DIR_APP', dirname(__DIR__)); // points to your project root

and use them in your include/require statements, e.g.

include (DIR_WEB . '/views/view1.php');
include (DIR_APP . '/private/privatefile.php');

This way you ALWAYS referring to the same file (using absolute path) regardless where that file is located.


You have to remember one thing: PhpStorm only performs static analysis -- it cannot do the same as PHP interpreter does (which works during run-time). Therefore IDE checks your include statements relative to either project/module root or actual script where it is used.

Using the above will satisfy both PhpStorm as well as PHP itself (you will be using full path, so no need to search for include files -- which is a bit faster -- can make some difference on very busy sites with lots of includes). Plus it's safer -- as you always refer to specific file so there is no chance that PHP will load similarly named file from another location by mistake.