开发者

Define root path one time at one place

开发者 https://www.devze.com 2023-03-25 23:17 出处:网络
I like to refer images, css and php files using their absolute path, that is starting from root, with an address beginning with \"/\".

I like to refer images, css and php files using their absolute path, that is starting from root, with an address beginning with "/".

I need to include php files that are all located at "/bin/res/include". I figured out I can't use absolute paths in php as I do in html. After some research I discovered the best method that suits my needs is to

define("PHP_ROOT", "/home/a7503679/public_html/bin/res/include/");

and then to include some file

include_once(PHP_ROOT."filename.php");

I don't want to paste the first define on every html page. Can I do a global define? Can I define that constant one time at one place and make it known to all html pages? If so, how and where is the global place?


  • I can't use dirname(__FILE__); because that only gives the full path to the folder where I'm currently in, which may not be the root.
  • I can't use $_SERVER['DOCUMENT_NAME'] because I'm using a shared hosting service.

[UPDATE:solution] thx everyone, especially RiaD for its idea, this is what I've 开发者_JAVA百科done:

Edited my .htaccess file at the root of my website and added the following line,

#Loads an init php located at <fullpath>/<path-to-folder-with-php-files-to-include>/init.php
php_value auto_prepend_file /home/a7503679/public_html/bin/res/include/init.php

Now all my html files will include that init.php file, so you should (as I did) put there all the common php code you'll need on every html page, which in my case was:

<?php
define("PHP_ROOT", "/home/a7503679/public_html/bin/res/include/"); #this solves the problem
include 'lang.php'; #translations file
?>

Before I needed to include that lang.php on every page and now it's automatically done. If I need to include any other php file, using its absolute path, I just type include PHP_ROOT.'filename.php';


You can use auto_prepend_file in your .htaccess

PS: $_SERVER['DOCUMENT_ROOT'] should work (on shared hostings too)


I think what you want to do is modify your include_path in php.ini to include your custom include path(s). Then you can just include files without any path qualifiers, and if they aren't present in the current directory, PHP will search your include paths for them. If you can't modify your php.ini, make a call to set_include_path in the configuration file that you know you're gonna have to include on every page anyway. :)


add the define to a include page that is included on every page like a config/database/language file

0

精彩评论

暂无评论...
验证码 换一张
取 消