Skip to content
Advertisement

Issues with directories and paths in a PHP project

I am having trouble figuring out this path problem. As you can see the highlighted tag is located in a file called admin_navigation.php and the href is going one directory up from includes folder which is admin and to the file posts.php. The absolute path seems correct to me and the to Phpstorm but the PHP server jumps to this location “http://localhost/cms/posts.php?source=add_post” but instead, it is supposed to go to “http://localhost/cms/admin/posts.php?source=add_post“. I’d appreciate it if someone can explain this weird behavior to me.

enter image description here

Advertisement

Answer

When you link files with include(), you’re not ‘referencing’ them per se, but copying the contents of the target file to the file with include().

Let’s say you’re including admin_navigation.php on /admin/index.php with include('includes/admin_navigation.php') or similar. This essentially copies the contents of admin_navigation.php into index.php. Now index.php contains the exact same link – <a href="../posts.php?source=add_post">add posts</a>.

As such, index.php looks one level up from /admin, and attempts to find posts.php in CMS — which it can’t, as the file doesn’t exist there.

Note that this process applies to every file that you include admin_navigation.php in, so if you have multiple references from multiple different folders, then you’ll have to have an absolute path in order for all files to reference the target correctly.

This would be done with <a href="/CMS/admin/posts.php?source=add_post">add posts</a>.

Alternatively, if you’re only including admin_navigation.php on files in the admin folder ( categories, index and posts), you can simply omit the parent folder navigation in the relative path: <a href="posts.php?source=add_post">add posts</a>.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement