Andrew T
Andrew T

Reputation: 79

php is not identifying the path correctly

I have this path tree (folders and files) in my application:

backend
    models
        some classes here
        .
        .
        .
        init.php
    views
       init.php
       users.php

includes
    page-content
        index-content.php
    header.php
    footer.php

index.php

Just to specify, I am not using any MVC framework, I just want to have my files organized like this.

Now, I am including index-content.php, header.php, footer.php in my index.php from the root path of the application and everything is working fine. Also, in header.php I am including init.php file from models folder and everything is working fine.

So what I want to do is for the view folder to have an init.php file (as you can see) that includes all the other files from views so that I could just include this init.php file than and that would be it. (so that i wouldn't have to include all the files from views folder everytime i'm using any of them). However, I'm getting an error that the file is not found.

So, in init.php from models folder i'm including init.php from views folder like this:

require_once("../views/init.php");

which for me it makes sense (out of the current folder (models), into the desired folder (views) and the file init.php from this folder.. But, i'm getting

( ! ) Warning: require_once(../views/init.php): failed to open stream: No such file or directory in C:\wamp64\www\s_top_navbar\backend\models\init.php on line 29

I don't understand why, as here is where the file is located. Also, VS Code is giving me autocompleting for this path as it is recognizing this file in this path.

I also tried to include it like

require_once("../backend/views/init.php");

and it still gives the same error..

Why doesn't it recognize the path?

Thank you!

Upvotes: 0

Views: 58

Answers (1)

tim
tim

Reputation: 2724

The path is not recognized because the current working directory is that of the executed script index.php in your app root.

See the PHP documentation for getcwd() and chdir().

You could use __DIR__ which returns the directory for the current script.

require_once __DIR__.'/../views/init.php';

I prefer defining the app root and use it for including scripts:

define('APP_ROOT', 'c:/path/to/app/root/');

require_once APP_ROOT.'backend/views/init.php';

Upvotes: 1

Related Questions