I have managed to get the URL of a managed file (that was uploaded via a form). The URL is as follows:

http://localhost/drupal/sites/default/files/myfile/Photo2015.06_27.jpg

I need to safely convert this to a file path on my system (so that I can use PHP's exec to use imagemagick on it). Of course I could write my own function to do this, however it's safer to use Drupal's build-in functions for this.

I looked at realpath() but it didn't seem to work.

Comments

CatsFromStonehenge’s picture

I gave up in the end, I'm not sure if this is safe, and it feels like a bit of a hack, but this works:

private function getLocalPathFromFileURL($file_url) {
  $decoded_file_url = rawurldecode($file_url);

  $host = \Drupal::request()->getHost();

  $file_system_path = str_replace("http://$host", '/var/www', $decoded_file_url);

  return $file_system_path;
}

Any suggestion on how to make this safer, or to use the Drupal built-in way, would be great :)

samoakley’s picture

PHP has realpath() you could have just used that on the URI to get the file path without having to use your function

edit: nvm just saw you said it didn't work for you, weird