Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

realpath

(PHP 4, PHP 5)

realpath -- Возвращает канонизированный абсолютный путь к файлу

Описание

string realpath ( string path )

realpath() раскрывает все символические ссылки, переходы типа '/./', '/../' и лишние символы '/' в пути path, возвращая канонизированный абсолютный путь к файлу. В этом пути не будет символических ссылок и компонентов типа '/./' или '/../'.

realpath() возвращает FALSE при неудаче, например если файл не существует.

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

<?php
$real_path
= realpath("../../index.php");
?>

См. также описание функций basename(), dirname() и pathinfo().



rename> <readlink
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
realpath
Zach Bernal zbernal at ucsc dot edu
17-Oct-2007 11:10
Santosh Patnaik's method worked in most cases, but when I gave it funky input with different directory separators it returned the wrong path. I liked julabz at laposte dot net the best, and modified it to use a similar signiture signature to Patnaik's function:

<?php

   
function unrealpath($start_dir, $final_dir, $dirsep = DIRECTORY_SEPARATOR){
       
       
//Directory separator consistency
       
$start_dir = str_replace('/',$dirsep,$start_dir);
       
$final_dir = str_replace('/',$dirsep,$final_dir);
       
$start_dir = str_replace('\\',$dirsep,$start_dir);
       
$final_dir = str_replace('\\',$dirsep,$final_dir);

       
//'Splode!
       
$firstPathParts = explode($dirsep, $start_dir);
       
$secondPathParts = explode($dirsep, $final_dir);
      
       
//Get the number of parts that are the same.
       
$sameCounter = 0;
        for(
$i = 0; $i < min( count($firstPathParts), count($secondPathParts) ); $i++) {
            if(
strtolower($firstPathParts[$i]) !== strtolower($secondPathParts[$i]) ) {
                break;
            }
           
$sameCounter++;
        }
       
//If they do not share any common directories/roots, just return 2nd path.
       
if( $sameCounter == 0 ) {
            return
$final_dir;
        }
       
//init newpath.
       
$newPath = '';
       
//Go up the directory structure count(firstpathparts)-sameCounter times (so, go up number of non-matching parts in the first path.)
       
for($i = $sameCounter; $i < count($firstPathParts); $i++) {
            if(
$i > $sameCounter ) {
               
$newPath .= $dirsep;
            }
           
$newPath .= "..";
        }
       
//if we did not have to go up at all, we're still in start_dir.
       
if( strlen($newPath) == 0 ) {
           
$newPath = ".";
        }
       
//now we go down as much as needed to get to final_dir.
       
for($i = $sameCounter; $i < count($secondPathParts); $i++) {
           
$newPath .= $dirsep;
           
$newPath .= $secondPathParts[$i];
        }
       
//
       
return $newPath;
    }

?>

The only error I found in julabz's function was that count is always 1 for any string, but strlen does what he intended in this case.
cjunge at author-it dot com
15-Oct-2007 04:18
eric at themepark dot com noted that realpath() strips off the trailing directory separator. This is only correct for PHP4!

PHP5 seems to have silently "corrected" this behaviour, now leaving the trailing separator. This can result in incorrect behaviour if your path isn't meant to contain a trailing separator.

eg:
PHP4: realpath("some/path/with/a/trailing/slash/") => "[root]/some/path/with/a/trailing/slash"

PHP5: realpath("some/path/with/a/trailing/slash/") => "[root]/some/path/with/a/trailing/slash/"
alex at bartl dot net
03-Oct-2007 08:25
Sometimes it is helpful to check for the existance of a file
which might be found by using the include_path like in

include("file_from_include_path.php");

A simple function iterates the include_path and tries all
possibilites, returns translated_local_path on success or false
if not found.

function mappath($path_to_translate){
  $IncludePath=explode(PATH_SEPARATOR,get_include_path());
  foreach($IncludePath as $prefix){
    if(substr($prefix,-1)==DIRECTORY_SEPARATOR)
      $prefix=substr($prefix,0,-1);
    $try_path=sprintf("%s%s%s"
      ,$prefix,DIRECTORY_SEPARATOR,$path_to_translate);
    if(file_exists($try_path))return($try_path);
  }
  return false;
}
alban dot lopez+php dot net at gmail dot com
21-Sep-2007 12:15
Here's a little function to return the shortest relative path between dest folder and current folder (you can be replace $_SERVER['PHP_SEFL'] by your variable folder) :

<?php
// if you run in /var/www/

echo UnRealPath ('./'); // return "./"
echo UnRealPath ('./ajax-browser/AJAX-B/scripts/'); // return "./ajax-browser/AJAX-B/scripts/"
echo UnRealPath ('/var/'); // return "./../"
echo UnRealPath ('/opt/picasa/wine/'); // return "./../../opt/picasa/wine/"

function UnRealPath ($dest)
{
   
$Ahere = explode ('/', realpath($_SERVER['PHP_SEFL']));
   
$Adest = explode ('/', realpath($dest));
   
$result = '.'; // le chemin retoun
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571