Since I change the tree, absolute and relative path don't work

后端 未结 2 2055
逝去的感伤
逝去的感伤 2021-01-26 04:58

I tried to use the absolute path to include my files :

I have 4 files (I have other file on my localhost but oddly the inclusion works well) :

header.php

2条回答
  •  北海茫月
    2021-01-26 05:18

    I tried to use the absolute path to include my files :

    header.php (C:\wamp\www\MySite\layout\header.php)

    The PHP code is executed on the server. An absolute path in this context means a file-system absolute path, not a web host path. Since you are on Windows, /pdo.php in fact means C:/pdo.php and not C:\wamp\www\MySite\pdo.php as it seems you think.

    The best way to work with paths in PHP, regarding include and require is to use the __FILE__ and __DIR__ magic constants and the dirname() PHP function to build the (file-system) absolute paths of files starting from their relative locations.

    Your code becomes:

    header.php (C:\wamp\www\MySite\layout\header.php):

    pdo.php (C:\wamp\www\MySite\pdo.php)

    dir1/dir2/dir3/file.php (C:\wamp\www\MySite\dir1\dir2\dir3\file.php)

    Remark

    The solution presented here makes the code independent of its actual location in the file system. You can move the entire project (everything in C:\wamp\www\MySite) in a different directory or on a different computer and it will work without changes. Even more, if you use forward slashes (/) as directory names separators it works on Windows, macOS or any Linux flavor.

提交回复
热议问题