Home > Article > Backend Development > PHP relative path problem
When requiring and including a file in PHP, relative paths are mostly used, which is a headache. │
│ │
│ └2.php
└index.php
Problem: In 1.php, include ("../B/2.php") is used to introduce the 2.php file in the B directory;
in In index.php, include ("A/1.php") is used to introduce the 1.php file in the A directory;
Of course there will be problems when running it, and the ../B/2.php file cannot be found.
Remember one principle, all include statements are eventually converted into include paths based on the include file path. It is recommended to use a basic path as a reference for all paths, such as __FILE__ or $_SERVER['DOCUMENT_ROOT']
__
FILE__: (suitable for various situations)Configure the site root directory in the config file
define( "WEB_ROOT ", dirname(__FILE__) );The config file is placed in the root directory of the website,
Other files include configuration files ,When including other files, just locate them according to WEB_ROOT.
require_once( WEB_ROOT . "/a.php " );$_SERVER['DOCUMENT_ROOT'], suitable for non-virtual host (Alias) situation Php code
<?php if (!defined("WETSITE_BASE_DIR")) define("WETSITE_BASE_DIR", $_SERVER['DOCUMENT_ROOT'].'/Clare/'); require_once(WETSITE_BASE_DIR.'includes/global.inc.php'); ?>