PHP - Smarter Files Referencing

淺唱寂寞╮ 提交于 2019-12-12 01:12:42

问题


I have some simple PHP scripts that helps me with small tasks on each of my servers. I run it via the CLI only, since not all my servers have Apache, but I install PHP on all. I'd like to make it portable, at any time.

Here's my scripting scheme:

dir_libs/top.php  (top.php references all my classes and functions)
dir_logs/  (holds logs I may create)
runstats.php  (this is what I initialize from CL)

Here's what I have done on one of my servers:

runstats.php

<?php
require('/home/myuser/public_html/dir_libs/top.php'); // holds functions
require('/home/myuser/public_html/dir_logs/'); // holds logs from my functions

 echo display_stats();
 echo "\n---------------------\n";
?>

I obviously need to change the absolute paths, depending on the server, since I don't always keep things the same - even if I clone a virtual machine.

I tried $_SERVER['DOCUMENT_ROOT'], but that appears to need a browser to know where it lies.

Does anyone have a suggestion?
Again, I only intend to run the runstats.php from the command-line.


回答1:


This is normally done in PHP using the __DIR__ magic constant, like this:

require_once(__DIR__ . '/path/to/file.php');

To get to your top-level from a different embedded directory, you can do something like this::

require_once(__DIR__ . '/../dir_libs/top.php');

For versions of PHP previous to 5.3.0, you can use dirname(__FILE__) in place of __DIR__.

For a real-world example, you can look at the Laravel project, which uses a few different tricks in the .php files found in the public and bootstrap directories to reference other files in the project:

https://github.com/laravel/laravel/tree/v4.1.18

(I've linked to the current version, in case it changes later on.)




回答2:


Store the path in a constant and then append that on to the file.

define('BASE', '/home/myuser/public_html/');
require(BASE . 'dir_libs/top.php');



回答3:


In php 4 the __FILE__ and __DIR__ constants hase been added. These should help you!

http://www.php.net/manual/en/language.constants.predefined.php



来源:https://stackoverflow.com/questions/21713924/php-smarter-files-referencing

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