PHP - Convert File system path to URL

后端 未结 11 1510
野的像风
野的像风 2020-11-29 08:12

I often find that I have files in my projects that need to be accessed from the file system as well as the users browser. One example is uploading photos. I need access to t

11条回答
  •  悲&欢浪女
    2020-11-29 08:44

    All answers here promotes str_replace() which replaces all occurences anywhere in the string, not just in the beginning. preg_replace() will make sure we only do an exact match from the beginning of the string:

    function remove_path($file, $path = UPLOAD_PATH) {
      return preg_replace("#^($path)#", '', $file);
    }
    

    Windows can be a problem where directory separators / and \. Make sure you replace the directory separators first:

    function remove_path($file, $path = UPLOAD_PATH) {
      $file = preg_replace("#([\\\\/]+)#", '/', $file);
      $path = preg_replace("#([\\\\/]+)#", '/', $path);
      return preg_replace("#^($path)#", '', $file);
    }
    

    I would play with something like the following. Make note of realpath() and rtrim().

    function webpath($file) {
      $document_root = rtrim(preg_replace("#([\\\\/]+)#", '/', $_SERVER['DOCUMENT_ROOT']), '/');
      $file = preg_replace("#([\\\\/]+)#", '/', realpath($file));
      return preg_replace("#^($document_root)#", '', $file);
    }
    
    echo webpath(__FILE__); // Returns webpath to self
    echo webpath('../file.ext'); // Relative paths
    echo webpath('/full/path/to/file.ext'); // Full paths
    

提交回复
热议问题