Root path variable in a PHP project

微笑、不失礼 提交于 2019-12-25 08:08:49

问题


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?


回答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.




回答2:


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');



回答3:


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));




回答4:


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';


来源:https://stackoverflow.com/questions/38867220/root-path-variable-in-a-php-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!