1
\$\begingroup\$

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?
\$\endgroup\$
1
  • \$\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
    Oct 31, 2017 at 23:36

1 Answer 1

1
\$\begingroup\$

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().

\$\endgroup\$
1
  • \$\begingroup\$ realpath is for paths and not for URLs! \$\endgroup\$
    – adilbo
    Oct 27, 2020 at 11:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.