\$\begingroup\$
\$\endgroup\$
1
Reading several questions regarding the topic, I made my function to return file's absolute path from the file URL. As I'm using this in an WordPress environment, hence I availed untrailingslashit()
in it.
/**
* Get file absolute path from URL.
*
* @author carlosveucv
* @link https://stackoverflow.com/a/17744219/1743124
*
* @param string $file_url File URL.
* @return string File path.
* --------------------------------------------------------------------------
*/
function wp20171021_get_file_path_from_url( $file_url ) {
$file_path = parse_url( $file_url, PHP_URL_PATH );
return wp_normalize_path( $_SERVER['DOCUMENT_ROOT'] . $file_path );
}
- How bulletproof is this?
- What kind of caveats this might have in real world?
- I tested this in Windows, so is it 'cross platform-friendly?
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 21, 2017 at 6:15
-
\$\begingroup\$ To determine if the code is bulletproof, you can imagine odd cases, expected result in such odd cases and check if your function returns the expected result. That's the principle of unit tests. You can check phpunit.de/getting-started.html, that's the de facto standard test runner for PHP. \$\endgroup\$Dereckson– Dereckson2017年10月31日 23:36:27 +00:00Commented Oct 31, 2017 at 23:36
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
This should be the most cross platform way and uses less memory (also doesn't depend on wp)
function get_file_path_from_url( $file_url ){
return realpath($_SERVER['DOCUMENT_ROOT'] . parse_url( $file_url, PHP_URL_PATH ));
}
It uses the native PHP function realpath().
-
\$\begingroup\$ realpath is for paths and not for URLs! \$\endgroup\$adilbo– adilbo2020年10月27日 11:44:34 +00:00Commented Oct 27, 2020 at 11:44
lang-php