How to store the root of my “subsite” [closed]

2019-03-04 03:15发布

问题:

I need to add my "web app" to an existing site. It will be placed in a separate folder.

What is the best way to define the root for my app? It will have no interaction with the rest of the site.

I thought of just creating a .php script in my root and do something like:

define('ROOT_DIR', dirname(__FILE__));

And then include this file in all other scripts.

Is this the right way to do it?

回答1:

FROM PHP DOC on dirname(__FILE__) or __DIR__

Given a string containing the path of a file or directory, this function will return the parent directory's path.

This can easily change depending on our be structure and one single config file

eg.

http://example.com = /public_html
http://example.com/mobile = /public_html/mobile

My Advice .. HARD CODE it since it is always fixed

define('ROOT_DIR','/public_html');

if you have a file in /public_html/class/HelloWord.class.php

You can easy access it has the following no matter your current directory

 ROOT_DIR . '/class/HelloWord.class.php' ;


回答2:

Your method is also correct but it is matter of personal choice. I prefer using absolute URL over relatives as I personally feel absolute URL are less error prone.

For any web application that we make in core PHP (without using any framework), we define a config.php file with two following entries (Obviously with other too)

$WEBPATH="http://www.example.com/";
$OSPATH="/home/user/public_html/";

First two lines on any other php file are:

if(!defined(ANY_VAR_SET_BY_VALID_FILES)) die 'Invalid file';
require_once('path/config.php');

After that, all the paths/URL use $WEBPATH or $OSPATH.