Creating php involves working in a subdirectory

Ok, I am creating an admin interface for my custom blog in url / admin.

Is it possible that I can use the same (including startup) as the root directory.

If possible, I would also like to be able to automatically correct links in navigation so that they can go to index.php in /changes../index.php when accessed from / admin.

Thanks Nico

+7
include directory php
source share
4 answers

The best practice for this is to define the constant "ABSOLUTE_PATH", which contains the directory in which everything is located. After that, you can simply copy and paste everything, because it defines the path "full", which does not change from directory to directory.

Example

define("ABS_PATH", $_SERVER['DOCUMENT_ROOT']); or define("ABS_PATH", dirname(__FILE__)); // This defines the path as the directory the file is in. 

Then at any point you can simply do this to include the file

 include(ABS_PATH . "/path/to/file"); 
+18
source share

The easiest way is to use absolute urls / urls.

For URLs, define a constant / variable somewhere that points to the root of your application, for example:

 define('ROOT_URL', 'http://www.example.com'); 

or

 $root_url = 'http://www.example.com'; 

And use it in every link, for example:

 <a href="{$root_url}/my-page.php">blah</a> 

Thus, it is always OK (and on the day when you install the project on another server or in a subdirectory, you only have one constant / variable to change, and it still works)

For inclusion / necessity always use absolute settings; one solution is to use dirname , for example:

 include dirname(__FILE__) . '/my_file.php'; include dirname(__FILE__) . '/../my-other-file.php'; 

__FILE__ - the current file in which you write this line; dirname gets the path (full path) to the directory containing this file.

With this, you never have to worry about the relative paths of your files.

+3
source share

Another answer would be similar to combining the first two sentences. You can define a constant:

 define('ABSPATH', dirname(__FILE__).'/'); 

Then, assuming config.php needs to be included in many site files, you can use the following statement for this:

 include(ABSPATH.'config.php'); 

Hope this helps.

0
source share

Another option I've used for functions.php in the past is the class autoloader.

 //Class Autoloader spl_autoload_register(function ($className) { $className = strtolower($className); $path = "includes/{$className}.php"; if (file_exists($path)) { require_once($path); } else { die("The file {$className}.php could not be found."); } }); 

This works under certain circumstances and has helped me in the past when I don't want to define an absolute root URL.

0
source share

All Articles