4

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?

jww
  • 97,681
  • 90
  • 411
  • 885
Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127

1 Answers1

11

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
  • 442,112
  • 142
  • 972
  • 1,088
  • 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 Fouladpour Jun 10 '10 at 10:27
  • @Majid ah, of course, it's a URL. parse_url() should work better for that: http://www.php.net/parse_url – Pekka Jun 10 '10 at 10:31
  • 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 Fouladpour Jun 10 '10 at 11:31
  • @Majid no problem! I added the information; if you have some example source code, feel free to add it in as well. – Pekka Jun 10 '10 at 11:33