PHP - Convert File system path to URL

后端 未结 11 1508
野的像风
野的像风 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:40

    The code below is well commented:

    function pathToURL($path) {
      //Replace backslashes to slashes if exists, because no URL use backslashes
      $path = str_replace("\\", "/", realpath($path));
    
      //if the $path does not contain the document root in it, then it is not reachable
      $pos = strpos($path, $_SERVER['DOCUMENT_ROOT']);
      if ($pos === false) return false;
    
      //just cut the DOCUMENT_ROOT part of the $path
      return substr($path, strlen($_SERVER['DOCUMENT_ROOT']));
      //Note: usually /images is the same with http://somedomain.com/images,
      //      So let's not bother adding domain name here.
    }
    echo pathToURL('some/path/on/public/html');
    

提交回复
热议问题