javascript - 如何从 JavaScript 中的服务器链接获取文件的直接链接?

标签 javascript php html ajax

所以,现在我有了一个文件。该文件位于 /home/johndoe/index.html

我使用 XAMPP 之类的东西进行托管,它在 localhost 托管文件夹 /home

这是我拥有的变量列表:

$server_addr = "localhost";
$server_root = "/home";
$file_dir = "/home/johndoe/index.html";

现在,在 PHP 中,我尝试获取访问 /home/johndoe/index.html 的链接。

我想做的事:

function getLink($file_dir, $server_addr, $server_root) {
    // Do something here
    return "SOMETHING HERE";
}

echo getLink("/home/johndoe/index.html", "localhost", "/home");
// Expect 'localhost/johndoe/index.html' here.

我认为只在事情上做事并不是明智的做法。

是否有任何 native 函数,或者如何通过“使用”文件来编写函数而不是对这三个字符串执行某些操作?

最佳答案

所以你基本上想获取 $server_addr,从中删除 $server_root 并将 localhost 放在它前面(我认为,是从我可以破译你的问题中收集到的 XD)

我会这样做:

首先,将 $server_root 从“/home”更改为“/home/”

然后:

//Variables to use
$server_addr = "localhost";
$server_root = "/home/";
$file_dir = "/home/johndoe/index.html";

//Function to get a click-able link
function getLink($file_dir, $server_addr, $server_root){
    
    //URL-ise? $server_addr
    $server_addr = 'http://' . $server_addr . '/';
    
    /**
     * Here we only want to replace the FIRST occurence of $server_root within $file_dir with $server_addr
     * */
    //Get the position of $server_root, in $file_dir, to make sure that it exists
    $root_pos = strpos($file_dir, $server_root);
    //Get the length of $server_root
    $root_len = strlen($server_root);
    
    //If it is not exactly (!==) equal to false (as 0 will be the case if it is at the very start)
    if($root_pos !== false){
        
        //Set the results by replacing only the first occurence
        $results = substr_replace($file_dir, $server_addr, $root_pos, $root_len);
        
        //Turn it in to a URL - Remove target="_blank" if you do not want it opening in a new tab
        $results = '<a href="' . $results . '" target="_blank">This is a link</a>';
        
        //Return the results
        return $results;
    }
}

echo getLink($file_dir, $server_addr, $server_root);

这将做什么:

获取“针”的长度和“针”起点的位置。

然后它将用替换内容替换从起始位置开始的所有内容(其长度)。

这是一种仅替换第一次出现的/home/的简单方法,以防实际 URL 中的某处有/home/。我选择此方法而不是 preg_replace 是因为您使用的变量可以包含任何内容,而 preg_replace 对于如此简单的事情来说有点繁重和复杂。

我希望这能起作用。

关于javascript - 如何从 JavaScript 中的服务器链接获取文件的直接链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30009915/

相关文章:

javascript - 打开一个窗口并在选项卡之间共享它?

javascript - mysql 查询数据未通过 ajax 从 php 正确传递到 javascript

javascript - 如何使用jquery获取div内链接的href?

javascript - 支持土耳其语输入的文本框

html - 使用 simple-line-icons 符号作为占位符

c# - 如何停止按钮上的页面刷新单击我正在使用更新面板,但它不起作用

javascript - Object.keys() 排序标准?

php - 登录可以从数据库获取任何数据但显示结果 "Unregister Account"

php - 如何使用 Gitlab API(使用 PHP curl)获取 Gitlab 存储库中子目录的内容

html - 垂直对齐图像顶部的中间和居中文本