PHP - Convert File system path to URL

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

    This simple snippet can convert the file path to file's url on the server. Some settings like protocol and port should be kept.

            $filePath = str_replace('\\','/',$filePath);
            $ssl = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? true : false;
            $sp = strtolower($_SERVER['SERVER_PROTOCOL']);
            $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
            $port = $_SERVER['SERVER_PORT'];
            $stringPort = ((!$ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':' . $port;
            $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
            $fileUrl = str_replace($_SERVER['DOCUMENT_ROOT'] ,$protocol . '://' . $host . $stringPort, $filePath);
    

提交回复
热议问题