PHP - Function to remove character and concatenate strings (relative URL to absolute)

0

Good people!

I have a small problem (problem because I do not work too much with php).

I'm using a phpbb-linked script that displays the topics of a particular forum on an external page, but cms returns me only the relative url (the script is in the root of the site and phpbb is installed in ./forum), with this can not create an rss for example, which requires me to absolute url.

The format returned by phpbb is ./forum/viewtopic.php?f=xx&t=xx

What I need is not even so deep in phpbb, but simply a way of transforming this relative path into an absolute path, simply remove that first point and add http://exemplo.com to that place, and then http://exemplo.com/forum/viewtopic.php?f=xx&t=xx .

How can I do a function to work this using php (maybe a function that uses regex, I do not know)?

Thank you in advance!

    
asked by anonymous 18.02.2016 / 22:13

2 answers

0

Well, as I mentioned above, the path I get is physical, and I need to convert to an absolute URL.

Anyway, an international stack user answered me :

$url = str_replace('./', 'http://example.com/', $url);

    
19.02.2016 / 01:33
0

The appropriate term is canonicalize or normalize url

Example routine to normalize a url:

function canonicalize_url($str)
{

    $protocol = '';

    if (strpos($str, 'http://') !== false) {
        $protocol = 'http://';
        $str = substr($str, 7);
    } else if (strpos($str, 'https://') !== false) {
        $protocol = 'https://';
        $str = substr($str, 8);     
    } else if (strpos($str, '//') === 0) {
        $protocol = '//';
        $str = substr($str, 2);     
    }

    if (strpos($str, '/..') !== false) {
        $str = explode('/', $str);
        $first = $str[0];
        $keys = array_keys($str, '..');

        foreach ($keys as $k => $v) {
            array_splice($str, $v - ($k * 2 + 1), 2);
        }

        if (empty($str)) {
            $str = array($first);
        } else {
            reset($str);
            if ($first != $str[0]) {
                array_unshift($str, $first);
            }
        }

        return $protocol.str_replace('./', '', implode('/', $str));
    }

    return $protocol.str_replace('./', '', $str);

}

// testando url absoluta (http, https e protocolo genérico //)
$url = 'https://www.foo.bar/folder1/../folder2/bar/../../..';
$url = 'http://www.foo.bar/folder1/../folder2/bar/../';
$url = '//www.example.com/folder1/../folder2/bar/../../..';

// testando exceço de recuos. A função detecta e impede o recuo além da raiz da url (virtualmente).
$url = '//www.example.com/folder1/../folder2/bar/../../../../../../../../';

// testando url relativa
$url = './folder1/folder2/';
echo canonicalize_url($url); //http://www.example.com/else

The above function does not identify duplicate slashes, for example http://www.foo.bar/..////pasta

    
19.02.2016 / 02:36