user3109875
user3109875

Reputation: 828

How to get full path from relative path

I'm trying to access a page from another domain, I can get all other html from php, but the files like images and audio files have relatives paths making them to be looked inside the local server whereas they're on the other server.

I've allowed cross-domain access though PHP from the other page.

header('Access-Control-Allow-Origin: *'); 

Then I use AJAX load to load that pages' content.

$('#local_div').load('page_to_load_on_side_B #div_on_that_page');

Now, the path looks like this:

../../user/6/535e55ed00978.jpg

But I want it to be full like.

http//:www.siteB.com/user/6/535e55ed00978.jpg

Correction: I have full access to both sites so I need to get the absolute paths from the site where these files are originating.

Upvotes: 0

Views: 1153

Answers (3)

user3714314
user3714314

Reputation: 21

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);
}

Also you can find below solution:

In general, there are 2 solutions to this problem:

1) Use $_SERVER["DOCUMENT_ROOT"] – We can use this variable to make all our includes relative to the server root directory, instead of the current working directory(script’s directory). Then we would use something like this for all our includes:

include($_SERVER["DOCUMENT_ROOT"] . "/dir/script_name.php");

2) Use dirname(FILE) – The FILE constant contains the full path and filename of the script that it is used in. The function dirname() removes the file name from the path, giving us the absolute path of the directory the file is in regardless of which script included it. Using this gives us the option of using relative paths just as we would with any other language, like C/C++. We would prefix all our relative path like this:

include(dirname(__FILE__) . "/dir/script_name.php");

You may also use basename() together with dirname() to find the included scripts name and not just the name of the currently executing script, like this:

script_name = basename(__FILE__);

I personally prefer the second method over the first one, as it gives me more freedom and a better way to create a modular web application.

Note: Remember that there is a difference between using a backslash “\” and a forward (normal) slash “/” under Unix based systems. If you are testing your application on a windows machine and you use these interchangeably, it will work fine. But once you try to move your script to a Unix server it will cause some problems. Backslashes (“\”) are also used in PHP as in Unix, to indicate that the character that follows is a special character. Therefore, be careful not to use these in your path names.

Upvotes: 0

ZeroWorks
ZeroWorks

Reputation: 1638

For this problem would use one of the following:

Server Side Approach

I would create a parameter in server B named for example abspath. When this param is set to 1 the script would start an output buffer ob_start() then before submiting would get ob contents with ob_get_clean() and finally using regular expressions make a replace of all urls for http//:www.siteB.com/. So, the script on server A would look like follows:

<?php

$abspath=(isset($_REQUEST["abspath"])?$_REQUEST["abspath"]:0);

if($abspath==1) ob_start();

// Do page processing (your actual code here)

if($abspath==1)
{
   $html=ob_get_clean();
   $html=preg_replace("\.\.\/\.\.\/", "http://siteb.com/");
   echo $html;
}

?>

So in client side (site A) your ajax call would be:

$('#local_div').load('page_to_load_on_side_B?abspath=1#div_on_that_page');

So when abspath param is set to 1 site B script would replace relative path (note I guessed all paths as ../..) to absolute path. This approach can be improved a lot.

Client Side Approach

This replace would be done in JavaScript locally avoiding changing Server B scripts, . The replacements in Javascript would be the same. If all relative paths starts with ../.. the regex is very simple, so in site A replace $('#local_div').load('page_to_load_on_side_B #div_on_that_page'); for the following (note that I asume all relatives urls starts with ../..):

$.get('page_to_load_on_side_B #div_on_that_page', function(data) {
    data=data.replace(/\.\.\/\.\.\//, 'http://siteb.com/');
    $('#local_div').html(data);
});

That will do the replacement before setting html to DIV so images will be loaded from absolute URL.

Ensure full CORS access to site B.

The second approach is clean than the first so I guess would use Javascript to do the replacements, both are the same only changes where the replace is done.

Upvotes: 1

Flash Thunder
Flash Thunder

Reputation: 12036

There is a PHP function that can make absolute path from relative one.

realpath()

If you mean URL path, simply replace all occurences of "../" and add domain in front.

Upvotes: 0

Related Questions