Aplicativos em PHP/Trabalhando em PHP com/Path
PATH
[editar | editar código]Exemplos simples de uso de funções para path do PHP
<?php $path=dirname(realpath($_SERVER['SCRIPT_FILENAME'])); $path=substr($path,0,-5); echo "<br>Path deste script sem 5 finais caracteres - " . $path; echo "<br><br>Diretório atual - ".dirname(__FILE__); echo "<br>Caminho completo do script atual - ".__FILE__; echo "<br>URL do script atual - " . "http://" . $_SERVER['HTTP_HOST'] . $HTTP_SERVER_VARS["SCRIPT_NAME"]; ?> <?php $path = "/etc/passwd"; $file = dirname($path); // $file is set to "/etc" ?> <?php $path = "/home/httpd/html/index.php"; $file = basename($path); // $file is set to "index.php" $file = basename($path, ".php"); // $file is set to "index" ?> <?php echo dirname($_SERVER["REQUEST_URI"]); ?>
Recebendo o Path Absoluto do Script Atual
dirname(__FILE__)
Recebendo o path relativo do webserver do script atual
function GetRelativePath($path)
{
$npath = str_replace('\\', '/', $path);
return str_replace(GetVar('DOCUMENT_ROOT'), '', $npath);
}
GetRelativePath(dirname(__FILE__));
<?php
if (DIRECTORY_SEPARATOR=='/')
$absolute_path = dirname(__FILE__).'/';
else
$absolute_path = str_replace('\\\\', '/', dirname(__FILE__)).'/';
?>
Resultará em um path absoluto no estilo UNIX que funciona também em PHP5 sob Windows.
Em algumas instalações (< 4.4.1) $_SERVER['REQUEST_URI'] não está configurado, usado o código para corrigir:
<?php
if (!isset($_SERVER['REQUEST_URI'])) {
$_SERVER['REQUEST_URI'] = substr($_SERVER['PHP_SELF'],1);
if (isset($_SERVER['QUERY_STRING'])) $_SERVER['REQUEST_URI'].='?'.$_SERVER['QUERY_STRING'];
}
?>
$my_uri = "http://" . $_SERVER['HTTP_HOST'] . $HTTP_SERVER_VARS["SCRIPT_NAME"];
// então
<?php echo ("$my_uri");?>
<?php
include("{$_SERVER['DOCUMENT_ROOT']}/includes/my_include.php");
?>
Você pode usar isso para receber o diretório pai:
dirname(dirname(__FILE__))
...include a file relative to file path:
include(dirname(__FILE__) . '/path/relative/file_to_include.php');
Isso colocará ambos os paths "www" e "file" de forma fácil para transportar o array.
<?php
// build the www path:
$me = $_SERVER['PHP_SELF'];
$Apathweb = explode("/", $me);
$myFileName = array_pop($Apathweb);
$pathweb = implode("/", $Apathweb);
$myURL = "http://".$_SERVER['HTTP_HOST'].$pathweb."/".$myFileName;
$PAGE_BASE['www'] = $myURL;
// build the file path:
strstr( PHP_OS, "WIN") ? $strPathSeparator = "\\" : $strPathSeparator = "/";
$pathfile = getcwd ();
$PAGE_BASE['physical'] = $pathfile.$strPathSeparator.$myFileName;
// this is so you can verify the results:
$www = $PAGE_BASE['www'];
$physical = $PAGE_BASE['physical'];
echo "$physical<p>";
echo "$www<p>";
?>
retornará algo como:
Windows:
F:\dev\Inetpub\wwwroot\somedirectory\index.php
http://devserver/somedirectory/index.php
Unix:
/home/somepathto/gieson.com/webroot/index.php
http://www.gieson.com/index.php
Path absoluto do script em execução
$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));