Php get resource path

How to get real path to a file in PHP, but WITHOUT following links?

PHP has a nice realpath() function, which can convert something like /dir1/dir2/../dir3/filename to /dir1/dir3/filename . The «problem» with this function is that in case /dir1/dir3/filename is not an actual file but merely a link to another file, PHP would follow that link and return the real path of the actual file. However, I actually need to get the real path of the link itself. All I need is to resolve complexities like /dir/.. in the path. How can I do it?

3 Answers 3

Wrote a function for your requirement.

function realpath_no_follow_link($str) < if (is_link($str)) < $pathinfo = pathinfo($str); return realpath_no_follow_link($pathinfo['dirname']) . '/' .$pathinfo['basename']; >return realpath($str); > 

Nice, but not good enough: if dir2 is a symbolic link to dir1 and $str is dir2/filename where filename is an actual file in dir1 , then is_link($str) will be FALSE , and so this function will still return the realpath() .

I was hoping to find an existing PHP function that does that, or else something simple along the lines of xdazz’s answer (but that would actually work the way I want it to). Having failed to find such an answer, I’ve written my own dirty function. I’d be happy to hear your comments and suggestions for improvement!

// return the contracted path (e.g. '/dir1/dir2/../dir3/filename' => '/dir1/dir3/filename') // $path: an absolute or relative path // $rel: the base $path is given relatively to - if $path is a relative path; NULL would take the current working directory as base // return: the contracted path, or FALSE if $path is invalid function contract_path($path, $rel = NULL) < if($path == '') return FALSE; if($path == '/') return '/'; if($path[strlen($path) - 1] == '/') $path = substr($path, 0, strlen($path) - 1); // strip trailing slash if($path[0] != '/') < // if $path is a relative path if(is_null($rel)) $rel = getcwd(); if($rel[strlen($rel) - 1] != '/') $rel .= '/'; $path = $rel . $path; >$comps = explode('/', substr($path, 1)); // strip initial slash and extract path components $res = Array(); foreach($comps as $comp) < if($comp == '') return FALSE; // double slash - invalid path if($comp == '..') < if(count($res) == 0) return FALSE; // parent directory of root - invalid path array_pop($res); >elseif($comp != '.') $res[] = $comp; > return '/' . implode('/', $res); > 

Источник

Читайте также:  Атрибут pattern

pathinfo

pathinfo() возвращает информацию о path в виде ассоциативного массива или строки, в зависимости от flags .

Замечание:

Подробнее о получении информации о текущем пути, можно почитать в разделе Предопределённые зарезервированные переменные.

Замечание:

pathinfo() оперирует входной строкой и не знает фактическую файловую систему или компоненты пути, такие как » .. «.

Замечание:

Только в системах Windows символ \ будет интерпретироваться как разделитель каталогов. В других системах он будет рассматриваться как любой другой символ.

pathinfo() учитывает настройки локали, поэтому для корректной обработки пути с многобайтными символами должна быть установлена соответствующая локаль с помощью функции setlocale() .

Список параметров

Если указан, то задаёт, какой из элементов пути будет возвращён: PATHINFO_DIRNAME , PATHINFO_BASENAME , PATHINFO_EXTENSION и PATHINFO_FILENAME .

Если flags не указан, то возвращаются все доступные элементы.

Возвращаемые значения

Если параметр flags не передан, то возвращаемый ассоциативный массив ( array ) будет содержать следующие элементы: dirname , basename , extension (если есть) и filename .

Замечание:

Если path содержит больше одного расширения, то PATHINFO_EXTENSION возвращает только последний и PATHINFO_FILENAME удаляет только последнее расширение. (смотрите пример ниже).

Замечание:

Если path не содержит расширения, то не будет возвращён элемент extension (смотрите ниже второй пример).

Замечание:

Если basename параметра path начинается с точки, то все последующие символы интерпретируются как расширение файла ( extension ) и имя файла filename будет пустым (смотрите третий пример).

Если указан параметр flags , будет возвращена строка ( string ), содержащая указанный элемент.

Примеры

Пример #1 Пример использования функции pathinfo()

$path_parts = pathinfo ( ‘/www/htdocs/inc/lib.inc.php’ );

echo $path_parts [ ‘dirname’ ], «\n» ;
echo $path_parts [ ‘basename’ ], «\n» ;
echo $path_parts [ ‘extension’ ], «\n» ;
echo $path_parts [ ‘filename’ ], «\n» ;
?>

Результат выполнения данного примера:

/www/htdocs/inc lib.inc.php php lib.inc

Пример #2 Пример с pathinfo() , показывающий разницу между null и отсутствием расширения

$path_parts = pathinfo ( ‘/path/emptyextension.’ );
var_dump ( $path_parts [ ‘extension’ ]);

$path_parts = pathinfo ( ‘/path/noextension’ );
var_dump ( $path_parts [ ‘extension’ ]);
?>

Результатом выполнения данного примера будет что-то подобное:

string(0) "" Notice: Undefined index: extension in test.php on line 6 NULL

Пример #3 Пример pathinfo() для файла, начинающегося с точки

Результатом выполнения данного примера будет что-то подобное:

Array ( [dirname] => /some/path [basename] => .test [extension] => test [filename] => )

Пример #4 Пример использования pathinfo() с разыменованием массива

Параметр flags не является битовой маской. Может быть предоставлено только одно значение. Чтобы выбрать только ограниченный набор разобранных значений, используйте деструктуризацию массива следующим образом:

[ ‘basename’ => $basename , ‘dirname’ => $dirname ] = pathinfo ( ‘/www/htdocs/inc/lib.inc.php’ );

var_dump ( $basename , $dirname );
?>

Результатом выполнения данного примера будет что-то подобное:

string(11) "lib.inc.php" string(15) "/www/htdocs/inc"

Смотрите также

  • dirname() — Возвращает имя родительского каталога из указанного пути
  • basename() — Возвращает последний компонент имени из указанного пути
  • parse_url() — Разбирает URL и возвращает его компоненты
  • realpath() — Возвращает канонизированный абсолютный путь к файлу

Источник

php get URL of current file directory

Might be an easy question for you, but I’m breaking my head over this one. I have a php file that needs to know it’s current directory url to be able to link to something relative to itself. For example, currently I know to get the current directory path instead of the url. When I use this I get the path:

/Applications/MAMP/htdocs/mysite/dir1/dir2/dir3 
http://localhost:8888/dir1/dir2/dir3 
  • http://localhost:8888/index.php calls: «http://localhost:8888/dir1/dir2/dir3/myfile.php»
  • «myfile.php» needs to know it’s place in the universe 🙂 «Where am I»
  • «myfile.php» should know it’s url location is «http://localhost:8888/dir1/dir2/dir3/»

In most modern web applications the URL bears no relevance to the filesystem whatsoever. just something to bear in mind.

@CD001 yes but in that case it would be impossibile to answer without more information. His desired output is actually matching the file path relative to the project directory

There’s some ambigutiy in what you’re asking because your question mentions «current directory url». The «current directory» and the URL can be totally different — there isn’t necessarily a direct relationship between the filesystem directory of the script and its URL.

5 Answers 5

For example if the URL is http://localhost/~andy/test.php

That’s enough to generate a relative URL.

If you want the directory your current script is running in — without the filename — use:

In the case above that will give you /~andy (without test.php at the end). See http://php.net/manual/en/function.dirname.php

Please note that echo getcwd(); is not what you want, based on your question. That gives you the location on the filesystem/server (not the URL) that your script is running from. The directory the script is located in on the servers filesystem, and the URL, are 2 completely different things.

Источник

Get an absolute file path

How to get a absolute file path php I have a folder abc and xyz. I am including the file a.php of abc in xyz folder using Ajax request by giving relative path which is like:

The file a.php contains some actions which are done using Ajax request. In xyz folder i want to perform same actions which are perform in abc folder, but when i try to perform those actions it is searching for files in xyz folder instead of abc, so the actions which i want to perform in xyz are not working. Please help me how to do this. Updated code:

$(function()< $.ajax(< type:"POST", url: "../xyz/a.php", data: < "Id": '' >, success: function(data) < $("#divId").html(data); >>); >); 

4 Answers 4

I recommend you do something like this in your config/index/bootstrap:

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

This way when you need to load files, from other locations, you make all the paths relative to the ROOT_DIRECTORY. for example:

require_once(ROOT_DIRECTORY . 'abc/xyz.php'); 

This will make file inclusions a LOT simpler and will allow you to move the entire project directory to another location ( production server for example ) without breaking any ‘path’ logic.

Seeing your code update, I see you’re really talking about the request from the javascript.. in that case just leave the full url to the file: url:’http://server.com/xyx/abc.php’

============================================================================== ======I====== __File__; C:\wamp\www\folder1\folder2\file.php $_SERVER['PHP_SELF']; /folder1/folder2/file.php //$_SERVER['PHP_SELF'] is the same as $_SERVER["REQUEST_URI"]; ======II====== getcwd(); C:\wamp\www\folder1\folder2\ dirname(); OUTPUTS NOTHING - EMPTY NOT ALLOWED basename(); OUTPUTS NOTHING - EMPTY NOT ALLOWED __dir__; C:\wamp\www\folder1\folder2 ======III====== getcwd( XXX ); OUTPUTS NOTHING - PARAMETER NOT ALLOWED getcwd( XXX ); OUTPUTS NOTHING - PARAMETER NOT ALLOWED getcwd( XXX ); OUTPUTS NOTHING - PARAMETER NOT ALLOWED dirname(__FILE__); C:\wamp\www\folder1\folder2 dirname($_SERVER['PHP_SELF']); /folder1/folder2 dirname(getcwd()); C:\wamp\www\folder1 dirname(dirname()); OUTPUTS NOTHING - EMPTY NOT ALLOWED dirname(basename()); OUTPUTS NOTHING - EMPTY NOT ALLOWED basename(__FILE__); file.php basename($_SERVER['PHP_SELF']); file.php basename(getcwd()); folder2 basename(dirname()); OUTPUTS NOTHING - EMPTY NOT ALLOWED basename(basename()); OUTPUTS NOTHING - EMPTY NOT ALLOWED ======IV====== on dirname dirname(dirname(__FILE__)); C:\wamp\www\folder1 dirname(dirname($_SERVER['PHP_SELF'])); /folder1 dirname(dirname(getcwd())); C:\wamp\www basename(dirname(__FILE__)); folder2 basename(dirname($_SERVER['PHP_SELF'])); folder2 basename(dirname(getcwd())); folder1; on basename dirname(basename(__FILE__)); . dirname(basename($_SERVER['PHP_SELF'])); . dirname(basename(getcwd())); . basename(basename(__FILE__)); file.php basename(basename($_SERVER['PHP_SELF'])); file.php basename(basename(getcwd())); folder2 ============================================================================== 

ONLY current FILE url (like: mysite.com/myfile.php)

Current url Fully (like: mysite.com/myfile.php?action=blabla

To get RealPath to the file (even if it is included) (change /var/public_html to your desired root)

for wordpress, there exist already pre-defined functions to get plugins or themes url.

Источник

PHP pathinfo

Summary: in this tutorial, you will learn how to use the PHP pathinfo() function to get the information on a file path.

Introduction to the PHP pathinfo() function

The PHP pathinfo() function accepts a file path and returns its components:

pathinfo ( string $path , int $flags = PATHINFO_ALL ) : array|stringCode language: PHP (php)

The pathinfo() function has two parameters:

  • $path is the file path from which you want to get the information.
  • $flags parameter specifies the part element to return.

The following table shows the valid flag values:

Flag Meaning
PATHINFO_DIRNAME Return the directory name
PATHINFO_BASENAME Return the base name
PATHINFO_EXTENSION Return the file extension
PATHINFO_FILENAME Return the file name (without the extension)

If you don’t pass the $flag argument, the pathinfo() function will return all components of a file path.

PHP pathinfo() function examples

Let’s take some examples of using the pathinfo() function.

1) Using the pathinfo() function to get all components of a file path

The following example uses the pathinfo() function to get the components of a file path:

 $path = 'htdocs/phptutorial/index.php'; $parts = pathinfo($path); print_r($parts);Code language: HTML, XML (xml)
Array ( [dirname] => htdocs/phptutorial [basename] => index.php [extension] => php [filename] => index )Code language: PHP (php)

2) Using the pathinfo() function to get only a specific component of a file path

The following example uses the pathinfo() function get the basename of a file path:

 $path = 'htdocs/phptutorial/index.php'; $basename = pathinfo($path, PATHINFO_BASENAME); echo $basename;Code language: HTML, XML (xml)
index.phpCode language: CSS (css)

3) Using the pathinfo() function to get the path components of a dot-file path

The following example uses the pathinfo() function to get components of the path of a dot-file:

 $path = '/htdocs/phptutorial/.gitignore'; $parts = pathinfo($path); print_r($parts);Code language: HTML, XML (xml)
Array ( [dirname] => /htdocs/phptutorial [basename] => .gitignore [extension] => gitignore [filename] => )Code language: PHP (php)

Summary

  • Use the PHP pathinfo() function to get the components of a file path including dirname, basename, filename, and extesion.

Источник

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