Home > Backend Development > PHP Tutorial > 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
Release: 2016-07-25 08:57:35
Original
1039 people have browsed it
  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.



source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template