Share: Do not use relative paths when require or include in PHP

Source: Internet
Author: User
  1. require_once ('.. /.. /lib/some_class.php ');
copy code

This is a disadvantage: it first looks for the specified PHP include path, and then finds the current directory. Therefore, too many paths are checked. If the script is included in a script from another directory, its base directory becomes the directory where the other script resides.

Another problem is that when a timed task runs the script, its parent directory may not be the working directory.

Therefore, the best choice 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 written dead.

Below, to improve, the path/var/www/project may also change, then every time you have to change it? No, you can use the __FILE__ constant, for example:

  1. define (' R OOT ', PathInfo (__file__, Pathinfo_dirname));
  2. require_once (ROOT. '.. /.. /lib/some_class.php ');
copy code

Now, no matter which directory you move to, such as a server that is moved to an extranet, the code will run correctly without changes. That is, the PathInfo and __file__ constants are used to implement the portable code.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.