PHP root with .htaccess

随声附和 提交于 2019-12-18 12:43:25

问题


I'm using 000webhost, which uses a public_html folder in the root folder as the visible root for the site. In that folder, I have an assets folder with some PHP scripts, and other folders with PHP index pages. Using require "/assets/includes/scriptname.php"; does not work, as it tries to find a sibling folder to public_html. I'm allowed to edit .htaccess to change the root folder relative to the PHP lookup, but I don't know how.

File tree:

public_html (within root, but simulated root)
   folder1
      index.php
   folder2
      index.php
   folder3
      index.php
   assets
      subfolder
      subfolder
   index.php

In short, how do I make the mentioned code point inside /public_html/ without explicitly declaring it (preferably as a .htaccess change, as I want my code to be able to be moved to a different host without rewriting anything).

For an answer with the .htaccess rewrite, could you explain how each line of it works? Thanks.


回答1:


.htaccess does not help you. It is an Apache configuration and it does not affect the behavior of PHP in any way.

The code:

require "/assets/includes/scriptname.php"

tells PHP to include a file using an absolute path. Using hardcoded absolute paths is not recommended because the code won't work when you move it into another directory or on a different server that has different paths.

The best way to specify the path of an included file is to generate it runtime, starting from the path of the includer. The PHP function dirname() and the constant __DIR__ are the helpers here.

Given the sample file structure:

public_html
   |
   +- index.php
   |
   +- assets
   |     |
   |     +- somescript.php
   |
   +- includes
         |
         +- header.php
         |
         +- footer.php

Let's say you need to include assets/somescript.php in index.php. Write this in index.php:

 require __DIR__.'/assets/somescript.php';

The magic constant __DIR__ contains the directory of the file where it is used. For index.php, __DIR__ is set to '/(...path-to-your-user-directory...)/public_html'.

If somescript.php needs to include header.php it should do it like this:

require dirname(__DIR__).'/includes/header.php';

and so on.

This way you can move the entire application to a different directory, on a different server and even on a different OS and it will still work.



来源:https://stackoverflow.com/questions/27680739/php-root-with-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!