Php path to script file

Path of the Current File in PHP

There are various methods of find the path of the current file in PHP. But the problem is to find one that is consistent across all servers. The following is a list of the most commonly used methods to find the location of the current file. The definitions are taken from the PHP manual(Predefined Variables) and are modified slightly.

The filename of the currently executing script, relative to the document root. For instance, $_SERVER[‘PHP_SELF’] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.

If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.

The query string, if any, via which the page was accessed.

The absolute pathname of the currently executing script.

Note: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER[‘SCRIPT_FILENAME’] will contain the relative path specified by the user.

Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it’s set to the same value as the SCRIPT_FILENAME server variable when it’s not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined.

Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.

Contains the current script’s path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.

The URI used to access this page; for instance, ‘/index.html’. Includes the query string.

__FILE__ The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path whereas in older versions it contained relative path under some circumstances.

Server PHP Version API $_SERVER[«PATH_INFO»] $_SERVER[«PATH_TRANSLATED»] $_SERVER[«PHP_SELF»] $_SERVER[«REQUEST_URI»] $_SERVER[«SCRIPT_FILENAME»] $_SERVER[«SCRIPT_NAME»] $_SERVER[«QUERY_STRING»] __FILE__
Microsoft-IIS/5.0 PHP 4.4.0 CGI/FastCGI /test/loc.php H:\\test\\loc.php /test/loc.php /test/loc.php hello=world H:\test\loc.php
Apache/2.0.52 (Fedora) PHP 4.3.9 Apache 2.0 Handler /var/www/htdocs/test/loc.php /test/loc.php /test/loc.php?hello=world /var/www/htdocs/test/loc.php /test/loc.php hello=world /var/www/htdocs/test/loc.php
Apache/2.0.55 (Unix) mod_ssl/2.0.55 OpenSSL/0.9.7a PHP/5.1.4 PHP 5.1.4 Apache 2.0 Handler /test/loc.php /test/loc.php?hello=world /var/www/htdocs/test/loc.php /test/loc.php hello=world /var/www/htdocs/test/loc.php
Apache/2.0.54 (Unix) PHP/4.4.4 mod_ssl/2.0.54 OpenSSL/0.9.7e mod_fastcgi/2.4.2 DAV/2 SVN/1.3.2 PHP 5.2.1 CGI/FastCGI /test/loc.php /test/loc.php?hello=world /home/binnyva/bin-co.com/test/loc.php /test/loc.php hello=world /home/xxxxxxxx/binnyva/bin-co.com/test/loc.php
Читайте также:  Load file java line by line

If you have access to a server that is not in the above list, please the below code to generate the results and send the result to me — I will include it here.

 header("content-type:text/plain"); 

$keys = array(
"PATH_INFO",
"PATH_TRANSLATED",
"PHP_SELF",
"REQUEST_URI",
"SCRIPT_FILENAME",
"SCRIPT_NAME",
"QUERY_STRING"
);

$info_row = " $_SERVER[SERVER_SOFTWARE] \n";
print
"Path Information for $_SERVER[SERVER_SOFTWARE]\n\n";

foreach(
$keys as $key) print '$_SERVER["'.$key.'"] = '.$_SERVER[$key]."\n";
$info_row .= " $_SERVER[$key] \n";
>

print
'__FILE__ = '. __FILE__;
$info_row .= "".__FILE__."\n";

print
"\n\n\n" . $info_row;

Источник

PHP Текущее местоположение скрипта, папки, имя файла

В языке PHP есть несколько полезных констант, которые мы можем применять в построении динамического пути к файлу или папке.

Как в PHP узнать полный путь к файлу или папке

Для начала приведу примеры, что вы получите вызвав соответствующие константы:

echo __FILE__; // /home/bitrix/www/bitrix/modules/main/admin/php_command_line.php echo __DIR__; // /home/bitrix/www/bitrix/modules/main/admin

Мы рассмотрели 2 константы, __FILE__ и __DIR__ для отображения полного пути к текущему файлу и папке (директории). Стоит отметить, что __DIR__ эквивалентен вызову:

echo dirname(__FILE__); // /home/bitrix/www/bitrix/modules/main/admin

dirname – это стандартная функция PHP, которая возвращает родительский каталог. Она применяется как раз для таких ситуаций, когда вам нужно узнать полный путь к файлу без самого файла :). Мне на ум пришла идея, как можно добиться такого же результата (не удивлюсь, если под капотом тоже самое):

echo str_replace(__FILE__, '',__DIR__); // /home/bitrix/www/bitrix/modules/main/admin

Что мы еще можем применить для константы __FILE__? Конечно же отделить путь и получить просто имя файла:

echo basename(__FILE__); // php_command_line.php

basename – функция возвращает последний элемент из пути, который, как правило, и является именем файла. Раз уж мы решили писать функции заменители, давайте рассмотрим наш URL, как массив, разделенный слешами (“/”):

$arPath = explode('/', __FILE__); // Array ( [0] => [1] => home [2] => bitrix [3] => www [4] => bitrix // [5] => modules [6] => main [7] => admin [8] => php_command_line.php

Как видим, последний элемент массива является нашим файлом. Чтобы получить последний элемент массива, не зная его количество, пишем:

$arPath = explode('/', __FILE__); echo $arPath[count($arPath)-1];

Минус 1 потому как отсчет для массивов идет с нуля, но при счете всегда стартует с единицы.
Важно – в некоторых указаниях полного пути вы используете разделители (вышеупомянутые слеши ‘/’). Но, для Windows это «\», для Linux и остальных — «/». Есть такая константа:

Вернет 1 слеш (без кавычек).

Немного закрепим 2 функции, о которых шла речь выше:
str_replace – функция, которая используется для замены в строке. Первый параметр “что ищем”, затем “на что меняем” и последний “где ищем”, в который мы и передали нашу полную строку.
explode – функция, которая делает из строки массив. Но, чтобы функции понять как разбить строку – ей нужно передать “разделитель”, а уже вторым параметром – саму строку.

Как вы заметили, “/home/bitrix/www” – это путь на самом сервере, который можно “вырезать” как раз при помощи str_replace.
Если вам нужно использовать “текущий домен”, то получить его при помощи PHP можно несколькими способами. Один из них:

echo $_SERVER['SERVER_NAME']; // site.com.ua

Надеюсь вам эта тема была интересна. Пишите в комментариях как вам формат, и нужен ли он вообще. А то в последнее время только битрикс да битрикс :).

Источник

Absolute & Relative Paths In PHP (A Simple Guide)

Welcome to a quick tutorial on absolute and relative paths in PHP. So you have set a verified file path, but PHP is still complaining about “missing” files and folders? Yes, it is easy to get lost in absolute and relative paths in PHP.

  • An absolute path refers to defining the full exact file path, for example, D:\http\project\lib\file.php .
  • While a relative path is based on the current working directory, where the script is located. For example, when we require «html/top.html» in D:\http\page.php , it will resolve to D:\http\html\top.html .

The covers the basics, but let us walk through more on how file paths work in PHP – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

TLDR – QUICK SLIDES

Absolute Relative Path In PHP

TABLE OF CONTENTS

PHP FILE PATH

All right, let us now get into the examples of how file paths work in PHP.

1) ABSOLUTE & RELATIVE PATH

  • An absolute file path is simply the “full file path”. Although a bit long-winded, it’s hard to mess up with this one.
  • On the other hand, the relative file path is based on the current working directory.

But just what the heck is the “current working directory”? Follow up with the next example.

2) CURRENT WORKING DIRECTORY (CWD)

In simple terms, the current working directory is the folder where the script is placed in. We can easily get the current working directory with the getcwd() function.

3) CONFUSION WITH THE CURRENT WORKING DIRECTORY

// (A) CWD IS BASED ON THE FIRST SCRIPT! // if this script is placed at "D:\http\inside\3-cwd.php" // cwd is "D:\http\inside" require "D:\\http\\2-cwd.php";

So far so good with relative paths? Now comes the part that destroyed many beginners, take note that this example script is placed at D:\http\inside . Guess what getcwd() shows when we run this example? Yes, the current working directory now changes to D:\http\inside . Keep in mind, the current working directory is fixed to the first script that runs .

4) CHANGING THE WORKING DIRECTORY

The current working directory will surely mess up a lot of relative paths. So, how do we fix this problem? Thankfully, we can use the chdir() function to change the current working directory.

5) MAGIC CONSTANTS

"; // (B) CURRENT FOLDER // if this file is placed at "D:\http\5-magic.php" // __DIR__ is "D:\http" echo __DIR__ . "
";
  • __FILE__ is the full path and file name where the current script is located.
  • __DIR__ is the folder where the current script is located.

6) MAGIC CONSTANTS VS WORKING DIRECTORY

"; // (B) CURRENT FOLDER // if this file is placed at "D:\http\inside\6-magic.php" // __DIR__ is "D:\http\inside" echo __DIR__ . "
"; // (C) GET PARENT FOLDER $parent = dirname(__DIR__) . DIRECTORY_SEPARATOR; require $parent . "5-magic.php";
  • The current working directory is based on the first script that we run.
  • Magic constants are based on where the scripts are placed in .

Yes, magic constants are the better way to do “pathfinding”, and to build absolute paths.

7) MORE PATH YOGA

"; // D:\http echo $_SERVER["PHP_SELF"] . "
"; // 7-extra.php echo $_SERVER["SCRIPT_FILENAME"] . "
"; // D:/http/7-extra.php // (B) PATH INFO $parts = pathinfo("D:\\http\inside\\index.php"); echo $parts["dirname"] . "
"; // D:\http\inside echo $parts["basename"] . "
"; // index.php echo $parts["filename"] . "
"; // index echo $parts["extension"] . "
"; // php // (C) BASENAME $path = "D:\\http\\inside"; echo basename($path) . "
"; // inside $path = "D:\\http\\inside\\foo.php"; echo basename($path) . "
"; // foo.php $path = "D:\\http\\inside\\foo.php"; echo basename($path, ".php") . "
"; // foo // (D) DIRNAME $path = "D:\\http\\inside\\"; echo dirname($path) . "
"; // D:\http echo dirname($path, 2) . "
"; // D:\ // (E) REALPATH echo realpath("") . "
"; // D:\http echo realpath("../") . "
"; // D:\

Finally, this is a quick crash course on the various variables and functions that may help you find the file path.

SERVER SUPERGLOBAL

  • $_SERVER[«DOCUMENT_ROOT»] – Contains the root HTTP folder.
  • $_SERVER[«PHP_SELF»] – The relative path to the script.
  • $_SERVER[«SCRIPT_FILENAME»] – The full path to the script.

PATH INFO

  • dirname – The directory of the given path.
  • basename – The filename with extension.
  • filename – Filename, without extension.
  • extension – File extension.

BASENAME

The basename() function will give you the trailing directory or file of a given path.

DIRNAME

The dirname() function will give you the parent directory of a given path.

REALPATH

The realpath() function gives you a canonicalized absolute path… Kind of useful, but still based on the current working directory.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

EXTRA) FORWARD OR BACKWARD SLASH?

Not really a big problem though, just use DIRECTORY_SEPARATOR in PHP and it will automatically resolve to the “correct slash”.

EXTRA) CASE SENSITIVE

  • We have a Foo.php script.
  • Windows is not case-sensitive – require «FOO.PHP» will work.
  • But Mac/Linux is case-sensitive – require «FOO.PHP» will throw a “file not found” error.
  • dirname – The directory of the given path.
  • basename – The filename with extension.
  • filename – Filename, without extension.
  • extension – File extension.

INFOGRAPHICS CHEAT SHEET

THE END

Thank you for reading, and we have come to the end of this guide. I hope it has helped you find the true path, and if you have anything to add to this guide, please feel free to comment below. Good luck and happy coding!

Источник

Оцените статью