Php find site root

Tarlyun blog

Часто возникает необходимость подгрузить из одного скрипта другой. Всё хорошо, когда эти скрипты физически расположены в одном каталоге. Делаем include и нет проблем. Проблемы возникают при развитой системе скриптов. Когда исполняемые файлы сгруппированы по каталогам и нужно настроить взаимодействие между ними.

Для себя я решил, что проще всего понять где находится корневой каталог и уже от него подгружать другие скрипты.

Способ 1. Некрасивый

Способ, которым я пользовался более трех лет. Основная идея: получить путь к каталогу текущего файла и относительно этого каталога подгружать другие скрипты.
В переменной $_SERVER[«SCRIPT_FILENAME»] содержится абсолютный путь к скрипту. С помощью функций mb_strrpos и mb_substr мы вырезаем из исходной строки имя файла. В итоге в константе PATH будет содержаться текущий каталог.

define ('PATH', mb_substr($_SERVER["SCRIPT_FILENAME"], 0, mb_strrpos($_SERVER["SCRIPT_FILENAME"], "/"))); require_once(PATH."/../connect.php");

define (‘PATH’, mb_substr($_SERVER[«SCRIPT_FILENAME»], 0, mb_strrpos($_SERVER[«SCRIPT_FILENAME»], «/»))); require_once(PATH.»/../connect.php»);

Плюсы данного решения

– Должен работать даже на самых древних версиях PHP.

– Инициализация константы происходит в одну строку.

Минусы данного решения

– В зависимости от вложенности скрипта, необходимо менять количество «../» . То есть, если вложенность один каталог:

require_once(PATH."/../connect.php");

Если вложенность 4 каталога:

require_once(PATH."/../../../../connect.php");

– Весь этот код вообще не нужен ведь, начиная с PHP 5.3, появилась константа __DIR__ , которая содержит путь к каталогу.

– При запуске скрипта с консоли в $_SERVER[«SCRIPT_FILENAME»] будет содержаться относительный путь. То есть, если вы запускаете скрипт так:

php /var/www/sites/lgnd.ru/public_html/parser/test.php

В $_SERVER[«SCRIPT_FILENAME»] будет содержаться полный путь.

Но если вы сначала перейдете в каталог скрипта, а затем запустите его:

cd /var/www/sites/lgnd.ru/public_html/parser/test.php php test.php

cd /var/www/sites/lgnd.ru/public_html/parser/test.php php test.php

то в $_SERVER[«SCRIPT_FILENAME»] будет содержаться только test.php

– На некоторых конфигурациях содержимое $_SERVER[«SCRIPT_FILENAME»] может быть пустым.

Способ 2. Элегантный, но не идеальный

В какой-то момент мне надоело постоянно менять вложенность. И я решил переписать этот говнокод.
Начиная с PHP 5.3, появилась удобная константа __DIR__ . Почему бы не воспользоваться ею?

Для начала определим: какое название имеет корневой каталог. В зависимости от настроек вашего веб-сервера, это может быть public_html , public , www или что-то другое. В константе __DIR__ будет такой путь:
/var/www/sites/lgnd.ru/public_html/parser

При помощи функции explode мы разобьем этот путь на две части. Разделителем будет служить название корневого каталога (в моем случае — public_html ). В итоге в $dir[0] будет содержаться левая часть (всё, что было до public_html ):
/var/www/sites/lgnd.ru/

К этой строке мы добавляем название корневого каталога и слэш.

$root_dir = 'public_html'; $dir = explode($root_dir, __DIR__); define ('PATH', $dir[0].$root_dir.'/'); require_once(PATH."/connect.php");

$root_dir = ‘public_html’; $dir = explode($root_dir, __DIR__); define (‘PATH’, $dir[0].$root_dir.’/’); require_once(PATH.»/connect.php»);

Плюсы

– Будет корректно определён путь до корневого каталога, вне зависимости от вложенности скрипта.

– Нет проблем с относительным/абсолютным путем при работе из командной строки или при запуске в экзотических конфигурациях

– Не нужно постоянно указывать дополнительные «../» при переносе скрипта в другой каталог.

Минусы

– Требует PHP 5.3+

– Инициализация занимает больше строк и её нельзя сократить (записать три строки в одну не комильфо)

– Требует указания корневого каталога, а значит скрипт нельзя просто скопировать с одного сервера на другой

Способ 3. Нет предела совершенству

Дальнейшие улучшения способа номер 2.

В PHP 5.4 появилось разыменование массивов. Эта штука позволяет обращаться к результатам работы функции explode без создания временной переменной:

$dir = explode('public_html', __DIR__); echo dir[0];

$dir = explode(‘public_html’, __DIR__); echo dir[0];

echo explode('public_html', __DIR__)[0];

echo explode(‘public_html’, __DIR__)[0];

В итоге код из способа 2 становится более компактным:

$root_dir = 'public_html'; define ('PATH', explode($root_dir, __DIR__)[0].$root_dir.'/');

$root_dir = ‘public_html’; define (‘PATH’, explode($root_dir, __DIR__)[0].$root_dir.’/’);

А если очень хочется всё записать в одну строку:

define ('PATH', explode('public_html', __DIR__)[0].'public_html'.'/');

define (‘PATH’, explode(‘public_html’, __DIR__)[0].’public_html’.’/’);

Источник

Get root url of the site in PHP

You have a known prefix (document root), an unknown (the root folder) and a known suffix (the script path), so to find the first two, you take the full absolute path ( ) and subtract the known suffix: If included files need this value, you must store this in a constant first before including the dependent scripts. . Using document root, the returned string is as follows when implemented on a website, which is not going to work if the link is to be shared, cause I am using it to store the file in a directory.

Get root url of the site in PHP

Consider my project directory structure as follows,

-public_html -projects -folder1 index.php \\code is written here +folder2 +downloads 

I am trying to get the root directory through $_SERVER[‘DOCUMENT_ROOT’] , but it seems the returned string is not in the form I expect.

My directory inside my website is (basically in) public_html/projects/folder1 . Using document root, the returned string is as follows when implemented on a website, /home/site_name/public_html which is not going to work if the link is to be shared, cause I am using it to store the file in a directory. So, I want something like it should return, www.site_name.com/downloads

The __DIR__ is giving the whole document path from where it is called( folder1/index.php ), but I want to get into the main folder ( public_html/downloads ), not in the same folder as the index file is.

Are there any other php functions that can help to reach the downloads folder in public_html and which can be accessed like, www.sitename.com/downloads/.

To return the folder of current php file, use this script.

$url = $_SERVER['REQUEST_URI']; //returns the current URL $parts = explode('/',$url); $dir = $_SERVER['SERVER_NAME']; for ($i = 0; $i < count($parts) - 1; $i++) < $dir .= $parts[$i] . "/"; >echo $dir; 

You want to use $_SERVER[‘SERVER_NAME’] to get the root URL of the site. You can use this to get a URL to your downloads folder.

$downloads_url = $_SERVER['SERVER_NAME'] . '/downloads/'; 
define('PROTOCOL',(!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://',true); define('DOMAIN',$_SERVER['HTTP_HOST']); define('ROOT_URL', preg_replace("/\/$/",'',PROTOCOL.DOMAIN.str_replace(array('\\',"index.php","index.html"), '', dirname(htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES))),1).'/',true);// Remove backslashes for Windows compatibility 

Then, in the the index of the project use it

PHP function to get the subdomain of a URL, PHP How to get the root url of a subdomain. See more linked questions. Related. 2773. How can I prevent SQL injection in PHP? 1283. Enumerations on PHP. 1234. Secure hash and salt for PHP passwords. 1911. How do I get PHP errors to display? 1250. Get the first element of an array. 2691.

PHP How to get the root url of a subdomain

I used to have my website into a domain like : www.mydomain.com
But now i’ve created a subdomain ‘test’ : www.test.mydomain.com and i moved the whole project files there.

So far so good, the problem is that on my php libraries where i call db connection etc, i use the $_SERVER[‘DOCUMENT_ROOT’] which gives me the URL without the subdomain , e.x.

$file = $_SERVER['DOCUMENT_ROOT'];//gives me www.mydomain.com 

But i need to get the root with the subdomain, like : www.test.mydomain.com

I dont want to make a trick like to split the url and add the subdomain thing.

Any help would be appreciated.

$_SERVER[‘DOCUMENT_ROOT’] does not contain the server name! It contains — as the name says — the DOCUMENT_ROOT . This is the directory where the filesystem starts that your webserver serves.

You should try $_SERVER[‘SERVER_NAME’] instead. This should work if your virtual server setup is correct.

$_SERVER["SERVER_NAME"] $_SERVER['HTTP_HOST'] 

Both will return the domain with the subdomain.

The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

Contents of the Host: header from the current request, if there is one.

You can read up on the difference between $_SERVER[«SERVER_NAME»] and $_SERVER[‘HTTP_HOST’] at HTTP_HOST vs. SERVER_NAME.

$_SERVER[‘DOCUMENT_ROOT’] will not work as stated in documentation

The document root directory under which the current script is executing, as defined in the server’s configuration file.

More information on $_SERVER at http://php.net/manual/en/reserved.variables.server.php.

Finally, after two hours searching , I spoke to the system admin and he cleared that he actually created an alias domain which it actually reacts as : www.test.mydomain.com .

I guess that is why i get the www.mydomain.com without the subdomain when i call $_SERVER[‘DOCUMENT_ROOT’] .

GET URL parameter in PHP, $_GET is not a function or language construct—it’s just a variable (an array). Try:

PHP get website root absolute URL in server?

I rely heavily in $_SERVER[«DOCUMENT_ROOT»] to get absolute paths. However this doesn’t work for sites which URLs don’t point to the root.

I have sites stored in folders such as:

all directly inside the root. Is there a way to get the path in the server where the current site root is?

 /var/chroot/home/content/02/6945202/html/site1 // If the site is stored in folder 'site1' /var/chroot/home/content/02/6945202/html // If the site is stored in the root 

You can simply append dirname($_SERVER[‘SCRIPT_NAME’]) to $_SERVER[‘DOCUMENT_ROOT’] .

The website seems to be directory «mounted» on that folder, so SCRIPT_NAME will obviously be / .

So, to make this work you have to use either __DIR__ or dirname(__FILE__) to find out where your script is located in the file system.

There’s no single index.php controller for the whole site, so that won’t work either.

The following expression does a string «subtraction» to find the common path. You have a known prefix (document root), an unknown (the root folder) and a known suffix (the script path), so to find the first two, you take the full absolute path ( __FILE__ ) and subtract the known suffix:

substr(__FILE__, 0, -strlen($_SERVER['SCRIPT_NAME'])); 

If included files need this value, you must store this in a constant first before including the dependent scripts. .

For future googlers, this also works for me

substr(substr(__FILE__, strlen(realpath($_SERVER['DOCUMENT_ROOT']))), 0, - strlen(basename(__FILE__))); 

Just use getcwd() for the current absolute server path of the folder the current script is in.

You can define a constant at the top of your website so that the rest of the website can rely on that path.

define('MY_SERVER_PATH', getcwd()); 

use the following method to get the absolute root url from your server settings

 str_replace($_SERVER['DOCUMENT_ROOT']."/",$_SERVER['PHPRC'],$_SERVER['REAL_DOCUMENT_ROOT']) 

or use the getcwd(). it gets the current working directory of your application

Getting the URL path to the directory of a file (PHP), Add a comment. 1. The steps for this are: Use dirname (__FILE__) to get the folder of the include file. Get the server root using $_SERVER [‘DOCUMENT_ROOT’] Remove the document root from the include folder to get the relative include folder. Obtain the server url.

Get Root Domain Name and subdomain Of Website using PHP

I am using this function code

public function getRootDomain($domain)

And the output i get is something like example.com but i want to show m.example.com or www.example.com Help related this ..thankx

Use parse_url() . You would want the host :

 The above example will output: array(3) < ["host"]=>string(15) "www.example.com" ["path"]=> string(5) "/path" ["query"]=> string(17) "googleguy=googley" > 
public function getRootDomain($domain)
public function getRootDomain($domain)

PHP: How to get referrer URL?, $_SERVER [‘HTTP_REFERER’] will give you the referrer page’s URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they’re not obliged to set the http_referer as well.

Источник

Читайте также:  Python int to one bytes
Оцените статью