简体   繁体   English

如何从绝对文件路径获取文件的 url 路径 - 将绝对路径转换为 ​​url 路径 - PHP

[英]How to get url path to file from absolute file path - Convert absolute path to url path - PHP

I have stored images path as absolute file path on server disk:我已将图像路径存储为服务器磁盘上的绝对文件路径:

/var/www/u1234567/data/www/somesampledomain.xyz/mediaimages/48fa6c736b75e1da485656e97b7d76f9.png

I want to convert this absolute path -> to url path like:我想将此绝对路径 -> 转换为 url 路径,如:

https://somesampledomain.xyz/mediaimages/48fa6c736b75e1da485656e97b7d76f9.png

I can just trim this unnessesary part with /var/www... .我可以用/var/www...修剪这个不必要的部分。 But is there some more univirsal way, without the hardcode part with /var/www/u1234567/data/www/ ?但是有没有更通用的方式,没有/var/www/u1234567/data/www/的硬代码部分?

I find it useful to have something like the below in the global config file:我发现在全局配置文件中包含以下内容很有用:

define('BASE_DIR', '/var/www/u1234567/data/www/somesampledomain.xyz/');
define('BASE_URL', 'https://somesampledomain.xyz/');

Which is useful for translating urls and paths, in various places.这对于在各个地方翻译 url 和路径很有用。 Though for simplicity it's usually more like:尽管为简单起见,它通常更像:

define('BASE_DIR', realpath('../htdocs/'));

Then you can:那么你也能:

$path = '/var/www/u1234567/data/www/somesampledomain.xyz/mediaimages/48fa6c736b75e1da485656e97b7d76f9.png';
$url  = 'https://somesampledomain.xyz/mediaimages/48fa6c736b75e1da485656e97b7d76f9.png';

function path_to_url($path) {
    return preg_replace('/^'.preg_quote(BASE_DIR, '/').'/', BASE_URL, $path, 1);
}

function url_to_path($url) {
    return preg_replace('/^'.preg_quote(BASE_URL, '/').'/', BASE_DIR, $url, 1);
}

var_dump(
    $url,
    path_to_url($path),
    $path,
    url_to_path($url)
);

Output:输出:

string(77) "https://somesampledomain.xyz/mediaimages/48fa6c736b75e1da485656e97b7d76f9.png"
string(77) "https://somesampledomain.xyz/mediaimages/48fa6c736b75e1da485656e97b7d76f9.png"
string(96) "/var/www/u1234567/data/www/somesampledomain.xyz/mediaimages/48fa6c736b75e1da485656e97b7d76f9.png"
string(96) "/var/www/u1234567/data/www/somesampledomain.xyz/mediaimages/48fa6c736b75e1da485656e97b7d76f9.png"

Ref:参考:

You can use this simple php script你可以使用这个简单的 php 脚本

<?php
$link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo("$link");
?>

It will show your full website url with current file like: http://site .com/file.php它将显示带有当前文件的完整网站 URL,例如: http://site .com/file.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM