tags:

views:

25

answers:

1

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?

+2  A: 

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.

Pekka
Thanks! This gets `[dirname]` correct, which was giving me troubles, but `[extension]` and `[filename]` are still incorrect. Anyway, my problem is solved as I was concerned with `[dirname]`, but I'd leave the question open for an hour to see if someone can get all components right.
Majid
@Majid ah, of course, it's a URL. parse_url() should work better for that: http://www.php.net/parse_url
Pekka
Thank you Pekka. Yes! So, I'd first use parse_url() to get a proper `path`, then I'd use pathinfo() on it. You may want to incorporate your solution into your answer so it is more useful to people later reading this, but if you don't find it worth the effort, I'd edit the question and include your method.
Majid
@Majid no problem! I added the information; if you have some example source code, feel free to add it in as well.
Pekka