112233
112233

Reputation: 2466

path to subfolders is confusing

My folder structure

root->
    my_framework-> inc / header.php
                             -> register / index.php

In the index.php which resides in register folder, how do I include header.php which is inside inc folder?

This seems to be very tricky.

I tried:

1) $_SERVER['DOCUMENT_ROOT'].'/my_framework/inc/header.php' = shows error saying no file found in that path

2) ../inc/header.php = no error but css not applicable. WHen view on source, path reads myframework/register/inc/header.php

3) $_SERVER['DOCUMENT_ROOT'].dir(_FILE_).'/inc/header.php' = path error

What is the correct way to include header which is inside inc folder in any subfolder?

Upvotes: 2

Views: 1820

Answers (2)

Progrock
Progrock

Reputation: 7485

1) $_SERVER['DOCUMENT_ROOT'].'/my_framework/inc/header.php' = shows error saying no file found in that path

2) ../inc/header.php = no error but css not applicable. WHen view on source, path reads myframework/register/inc/header.php

3) $_SERVER['DOCUMENT_ROOT'].dir(_FILE_).'/inc/header.php' = path error

1. This looks like it should work but relies on $_SERVER['DOCUMENT_ROOT']. Which you might not have if you were running from the command line. Did you echo the constant? Or the path?

2. Relative path issues.

If in header you have css path as: static/stylesheet.css. On the index page in my_framework the path resolves to /my-framework/static/stylesheet.css. On the register index page it would become /my-framework/register/static/stylesheet.css. It's easier to base all your paths from your web root (initial slash). /my-framework/static/stylesheet.css.

You can create a variable in your header called something like $base and prefix that to your web paths. $base = '/my_framework' then later href="<?php echo $base; ?>/static/stylesheet.css". Bear in mind for links. Needed if you move your site about during development and use sub-folders.

3. It's dirname(__FILE__) not dir(_FILE_). Magic constants have double underscores. You can switch out dirname(__FILE__) for __DIR__. This is a file system path. You may need to use this if your relative include paths don't appear to resolve.

Concatenating your document root with __DIR__ also doesn't make sense, you'll end up with something like: /var/www/var/www/foo/bar.

Upvotes: 1

Mihai Matei
Mihai Matei

Reputation: 24276

You can do it like this:

include('../inc/header.php');

The css is not working probably because you are using relative paths. Change the paths of the css and js files to /path/to/css-file.css

Upvotes: 3

Related Questions