Getting Relative Path from Absolute Path in PHP

Getting relative path from absolute path in PHP

Try this one:

function getRelativePath($from, $to)
{
// some compatibility fixes for Windows paths
$from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
$to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
$from = str_replace('\\', '/', $from);
$to = str_replace('\\', '/', $to);

$from = explode('/', $from);
$to = explode('/', $to);
$relPath = $to;

foreach($from as $depth => $dir) {
// find first non-matching dir
if($dir === $to[$depth]) {
// ignore this directory
array_shift($relPath);
} else {
// get number of remaining dirs to $from
$remaining = count($from) - $depth;
if($remaining > 1) {
// add traversals up to first matching dir
$padLength = (count($relPath) + $remaining - 1) * -1;
$relPath = array_pad($relPath, $padLength, '..');
break;
} else {
$relPath[0] = './' . $relPath[0];
}
}
}
return implode('/', $relPath);
}

This will give

$a="/home/a.php";
$b="/home/root/b/b.php";
echo getRelativePath($a,$b), PHP_EOL; // ./root/b/b.php

and

$a="/home/apache/a/a.php";
$b="/home/root/b/b.php";
echo getRelativePath($a,$b), PHP_EOL; // ../../root/b/b.php

and

$a="/home/root/a/a.php";
$b="/home/apache/htdocs/b/en/b.php";
echo getRelativePath($a,$b), PHP_EOL; // ../../apache/htdocs/b/en/b.php

and

$a="/home/apache/htdocs/b/en/b.php";
$b="/home/root/a/a.php";
echo getRelativePath($a,$b), PHP_EOL; // ../../../../root/a/a.php

Way to get absolute path of file PHP

You can try like this

include dirname(__FILE__).'/../yourfile.php';

Since PHP 5.3.0 you can use also the magic constant __DIR__ More info in the docs

Another way is

$rootDir = realpath($_SERVER["DOCUMENT_ROOT"]);

include "$rootDir/yourfile.php";

Absolute (or relative?) path in PHP

is there native function, if possible?

no. The document root is the only thing you can get from PHP. (Note however that in your scenario, you can simply call include("b.php"); because the script is still in the context of index.php.)

Re your update:

You can define a global application root in a central configuration file. Say you have config.php in your app root. Then do a

define("APP_ROOT", dirname(__FILE__));

you still have to include the config file, and you have to use relative paths for it, e.g.

include ("../../../config.php");

but once you have done that, you can work relative to the app root inside the script:

include (APP_ROOT."/b.php");  <--  Will always return the correct path

php relative and absolute paths

I usually set a constant, either manually or like this:

define('ROOT', dirname(__FILE__));

Then do

require ROOT . '/include/file.php';

To convert an absolute path to a relative path in php

The problem is that your question, although it seems very specific, is missing some crucial details.

If the script you posted is always being executed, and you always want it to go to delapo.com instead of temiremi.com, then all you would have to do is replace

$site_url    = "http://".$_SERVER["HTTP_HOST"]."$sitefolder";

with

$site_url    = "http://www.delapo.com/$sitefolder";

The $_SERVER["HTTP_HOST"] variable will return the domain for whatever site was requested. Therefore, if the user goes to www.temiremi.com/myscript.php (assuming that the script you posted is saved in a file called myscript.php) then $_SERVER["HTTP_HOST"] just returns www.temiremi.com.

On the other hand, you may not always be redirecting to the same domain or you may want the script to be able to adapt easily to go to different domains without having to dig through layers of code in the future. If this is the case, then you will need a way to figuring out what domain you wish to link to.

If you have a website hosted on temiremi.com but you want it to look like you are accessing from delapo.com, this is not an issue that can be resolved by PHP. You would have to have delapo.com redirect to temiremi.com or simply host on delapo.com in the first place.

If the situation is the other way around and you want a website hosted on delapo.com but you want users to access temiremi.com, then simply re-writing links isn't a sophisticated enough answer. This strategy would redirect the user to the other domain when they clicked the link. Instead you would need to have a proxy set up to forward the information. Proxy scripts vary in complexity, but the simplest one would be something like:

<?php
$site = file_get_contents("http://www.delapo.com/$sitefolder");
echo $site;
?>

So you see, we really need a little more information on why you need this script and its intended purpose in order to assist you.

HTML-PHP Relative Path to Absolute Path

I ilke @charlietfl's solution. However, somehow I think it gives more sense to manipulate the scraped content serverside before passing it to the client. You can do that by using DomDocument.

The following code converts all <img> src relative paths to absolute paths before echoing the result. Use the same approch for the <a> tags href attributes and so on,

error_reporting(0); //suppress DOM errors
$basePath='http://www.developphp.com/'; //use parse_url to get the basepath dynamically
$content=file_get_contents('http://www.developphp.com/view_lesson.php?v=338');
$dom=new DomDocument();
$dom->loadHTML($content);
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
$src=$image->attributes->getNamedItem("src")->value;
if (strpos($basePath, $src)<=0) {
$image->attributes->getNamedItem("src")->value=$basePath.$src;
}
}
echo $dom->saveHTML();

php finding file with relative but not with absolute path

UPDATED

$link3 is not working because file_exists() is looking for /folder/ all the way back to your root. file_exists() doesn't treat (relative) paths the same way the browser does.

So file_exists('/folder/image.png') isn't stemming off your public directory, it's rooting all the way back in the same fashion you would expect by entering in /home/username/public_html/ or /var/www/website/ know what I mean?

Entering in file_exists('/path/to/your/public/dir/folder/image.png'); would work.

And file_exists() will always return false if trying to add an http:// link to your asset in question. It only resolves absolute paths in the server directory path structure.



Related Topics



Leave a reply



Submit