0

I created a php project like this:

  • img
  • js
  • php
    • config
      • config.php
    • pages
      • news.php
      • contact.php

I need to include my config.php into all my files news.php, contact.php

How to avoid to have a relative path like ../config/config?

I would like to have a root path like php/config/config.php.

I use MAMP Pro. Should I use an environment variable to save the root path?

4 Answers 4

1

In PHP there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:

 $_SERVER['DOCUMENT_ROOT']

The only problem is that the entries in this variable are provided by the web server and there is no guarantee that all web servers offer them.

Sign up to request clarification or add additional context in comments.

Comments

1

Make a folder in your root. Name it e.g. Helpers/. Make a file in it path.php and inside it put this code.

function base_path($path = "") {
    return realpath(__DIR__ . '/../') . DIRECTORY_SEPARATOR . $path;
}

then include this file at the top of your every web document same as you do for your session start and then you can use this function any where in your code. Like so

<?php 

require "Helpers/path.php";

require base_path('php/config/config.php');

1 Comment

In this case, I'm going to have the same problem with require "Helpers/path.php", or not?
0

Create a constant with absolute path to the root by using define in ShowInfo.php:

define('ROOTPATH', DIR); OR (PHP <= 5.3)

define('ROOTPATH', dirname(FILE));

1 Comment

I need to create this constant in a file, and need to include this file in all my files ?
0

1 Find out your document root. This value is the same for all your scripts

echo $_SERVER['DOCUMENT_ROOT']; exit;

2 Use the path relative to the document root whenever you include config.php (adjust the line below once you know your document root)

require_once $_SERVER['DOCUMENT_ROOT'].'/php/config/config.php';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.