首页 > 解决方案 > 使用 PHP 和 Ajax 返回文件地址

问题描述

我有这样的 PHP 文件:

<?php
function getDirContents($directories, &$results = array()){

    $length = count($directories);
    for ($i = 0; $i < $length; $i++) {

    $files = array_diff(scandir($directories[$i]), array('..', '.'));;
    foreach($files as $key => $value){
        $path = $directories[$i].DIRECTORY_SEPARATOR.$value;
        if(is_dir($path)) {
          getDirContents([$path], $results);
        } else {
          $directory_path = basename($_SERVER['REQUEST_URI']);
          $results[] =  'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
        }
    }

    }

    return $results;
}

echo json_encode(getDirContents($_POST['directories']));

我有一个像这样的 ajax 调用命中上面的 PHP 文件:

function getURLs(directories) {
    $.ajax({
            type: 'POST',
            url: 'https://localhost/preload.php',
            data: {id: "testdata", directories: directories},
            dataType: 'json',
            cache: false,
            success: function(result) {
                // here is the result
                console.log(result);
            },
    });

}

正如您使用上面的代码所看到的,我们能够检索服务器上给定文件夹数组的所有文件地址,例如,如果文件夹中有两个文件名为1-1.mp3sample.pnghttps://localhost/sources/folder那么我们可以从 Ajax 调用中获取:

getURLs([sources/folder]); 
// returns : ['https://localhost/sources/folder/1-1.mp3', 'https://localhost/sources/folder/sample.png']

如果你给它一个要搜索的文件夹数组,这个函数就可以正常工作,但是如果你给它一个文件地址,它就不会返回结果,这就是问题所在

getURLs([sources/folder/1-1.mp3]); //returns nothing

如果当然存在,我希望上述函数也返回文件地址:

'https://localhost/sources/folder/1-1.mp3'

所以最终函数将返回服务器上存在文件文件夹数组的地址。(我们想添加文件搜索功能,因为文件夹搜索工作正常)

我们如何修改 PHP 代码来做到这一点?

标签: javascriptphpajax

解决方案


推荐阅读