Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP pathinfo gets fooled by url in query string, any workaround?

Tags:

php

pathinfo

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?

like image 502
Majid Fouladpour Avatar asked Dec 29 '22 14:12

Majid Fouladpour


1 Answers

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.

like image 92
Pekka Avatar answered Dec 31 '22 17:12

Pekka