Question

I am working on a small function to take in a url and return a relative path based on where it resides itself.

If the url contains a path in the query string, pathinfo returns incorrect results. This is demonstrated by the code below:

$p = 'http://localhost/demos/image_editor/dir_adjuster.php?u=http://localhost/demos/some/dir/afile.txt';
$my_path_info = pathinfo($p);
echo $p . '<br/><pre>';
print_r($my_path_info);
echo '</pre>';

That code outputs:

http://localhost/demos/image_editor/dir_adjuster.php?u=http://localhost/demos/some/dir/afile.txt

Array
(
    [dirname] => http://localhost/demos/image_editor/dir_adjuster.php?u=http://localhost/demos/some/dir
    [basename] => afile.txt
    [extension] => txt
    [filename] => afile
)

Which obviously is wrong. Any workaround?

Was it helpful?

Solution

Any workaround?

Yeah, doing it right ;)

$url = urlencode('http://localhost/demos/some/dir/afile.txt');
$p = 'http://localhost/demos/image_editor/dir_adjuster.php?u='.$url;

and for URLs, especially those with query strings, parse_url() should be more reliable to extract the path component; After that, run the pathinfo() on it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top