Home  >  Article  >  Backend Development  >  Share: Do not use relative paths when requiring or including in PHP

Share: Do not use relative paths when requiring or including in PHP

WBOY
WBOYOriginal
2016-07-25 08:57:35968browse
  1. require_once('../../lib/some_class.php');
Copy code

Disadvantages of this way of writing: It first looks for the specified php include path and then the current directory. So too many paths are checked. If the script is included by a script in another directory, its base directory becomes the directory where the other script is located.

Another problem is: when the scheduled task runs the script, its parent directory may not be the working directory.

So the best option is to use an absolute path, for example:

  1. define('ROOT' , '/var/www/project/');
  2. require_once(ROOT . '../../lib/some_class.php');
Copy code

The above code defines an absolute path, and the value is hard-coded.

Next, with improvements, the path /var/www/project may also change, so do you need to change it every time? No, you can use the __FILE__ constant, for example:

  1. define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
  2. require_once(ROOT . '../../lib/some_class.php');
Copy code

Now , no matter which directory it is moved to, such as moving it to an external server, the code will run correctly without any changes. That is to say, pathinfo and __FILE__ constants are used to achieve portable code.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn