peterpostmann/fileuri

从(相对)路径返回文件uri

1.0.0 2017-11-05 11:20 UTC

This package is not auto-updated.

Last update: 2024-09-11 08:18:41 UTC


README

Software License Build Status

从(相对)路径返回文件uri

安装

通过Composer

composer require peterpostmann/fileuri

如果你不想使用Composer,只需复制fileuri.php文件并将其包含到你的项目中。

原因

此函数可用于创建RFC3986兼容的文件URI并构建协议无关的功能。

function parseReference($ref)
{
    list($prefix, $path) = explode('://', $ref, 2);
    return [$prefix, $path];
}

var_dump(parseReference('https://server.tld/path/ressource.ext'));
var_dump(parseReference('file:///path/to/file.ext'));

上面的示例将输出


array (size=2)
  0 => string 'https' (length=5)
  1 => string 'server.tld/path/ressource.ext' (length=29)


array (size=2)
  0 => string 'file' (length=4)
  1 => string '/path/to/file.ext (length=17)

如果你想检查多个协议的URI,这不容易做到,因为PHP不返回符合rfc3986规范的文件URI。PHP返回的格式取决于文件位置和平台(https://php.ac.cn/manual/en/wrappers.file.php

use Sabre\Uri;

function parseReference($uri)
{
    return Uri\parse($uri);
}

用法

use function peterpostmann\fileuri;

string fileuri ( string path [, string basePath] ) 

示例

示例输出

use function peterpostmann\fileuri;

// Absolute Path
echo fileuri('/path/to/file.ext');
echo fileuri('C:\path\to\winfile.ext');
echo fileuri('\\\\smbserver\share\path\to\winfile.ext');

// Relative Path with base path
echo fileuri('relative/path/to/file.ext', '/');
echo fileuri('fileInCwd.ext','C:\testfolder);

// Path that is already a URI
echo fileuri('file:///path/to/file.ext');

上面的示例将输出


file:///path/to/file.ext
file:///C:/path/to/winfile.ext
file:///C:/path/to/winfile.ext
file://smbserver/share/path/to/winfile.ext
file:///relative/path/to/file.ext
file:///C:/testfolder/fileInCwd.ext
file:///path/to/file.ext

错误输出

如果提供了没有基本路径的相对路径,则函数返回false。

use function peterpostmann\fileuri;

// Relative Path without base path
var_dump(fileuri('relative/path/to/file.ext'));

上面的示例将输出


boolean false

与文件函数一起使用

use function peterpostmann\fileuri;

// Absolute Path
$uri = fileuri('/path/to/file.ext');

var_dump(file_get_contents(urldecode($uri)));

file_get_contents不规范化URL,因此无法直接使用文件URI。

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件