文章目录
在PHP中,URI scheme或称为伪协议,允许你通过不同的方式访问资源。下面我将详细介绍这些伪协议,并给出一些基本的使用示例。
1. file://
- 访问本地文件系统
用于读取或写入本地文件系统中的文件。
<?php
$contents = file_get_contents('file:///path/to/file.txt');
echo $contents;
?>
2. http://
和 https://
- 访问HTTP(s)网址
用于从Web服务器获取数据。
<?php
$contents = file_get_contents('http://example.com');
echo $contents;
?>
3. ftp://
- 访问FTP(s) URLs
用于通过FTP协议访问文件。
<?php
$stream = fopen('ftp://user:password@host/path/to/file', 'r');
if ($stream !== false) {
while (!feof($stream)) {
echo fgets($stream);
}
}
fclose($stream);
?>
4. php://
- 访问各个输入/输出流
用于处理标准输入和输出。
<?php
// 读取标准输入
$input = file_get_contents('php://stdin');
// 写入标准输出
fwrite(STDOUT, "Hello, World!\n");
// 写入标准错误输出
fwrite(STDERR, "An error occurred.\n");
?>
5. zlib://
- 压缩流
用于压缩或解压缩数据。
<?php
$compressed = gzencode("Hello, World!", 9);
$decompressed = gzdecode($compressed);
echo $decompressed;
?>
6. data://
- 数据(RFC 2397)
直接在URL中嵌入数据。
<?php
$data = "Hello, World!";
$encodedData = base64_encode($data);
$url = "data:text/plain;base64," . $encodedData;
$contents = file_get_contents($url);
echo $contents;
?>
7. glob://
- 查找匹配的文件路径模式
用于查找匹配指定模式的文件列表。
<?php
$files = glob('/path/to/directory/*.txt');
foreach ($files as $file) {
echo $file . "\n";
}
?>
8. phar://
- PHP归档
用于读取或写入PHAR文件。
<?php
$archive = new Phar('archive.phar');
$archive->buildFromDirectory('/path/to/directory');
?>
9. ssh2://
- Secure Shell 2
用于通过SSH协议执行命令或传输文件。
<?php
$connection = ssh2_connect('host', 22);
ssh2_auth_password($connection, 'user', 'password');
$stream = ssh2_exec($connection, 'ls');
stream_set_blocking($stream, true);
while (!feof($stream)) {
echo fgets($stream);
}
?>
10. rar://
- RAR
用于读取RAR归档文件。
<?php
$archive = new Phar('archive.rar', 0, 'archive.rar');
$archive->extractTo('/path/to/destination');
?>
11. ogg://
- 音频流
用于处理OGG音频格式。
这个伪协议实际上并不被PHP直接支持,可能是指向某些库的功能,如FFmpeg,用于处理音频流。
12. expect://
- 处理交互式的流
用于处理需要交互式输入的流,如telnet会话。
请注意,使用这些伪协议时,你需要确保你的PHP环境已经安装了相应的扩展,并且这些扩展已经被激活。例如,
ssh2://
要求有php-ssh2
扩展,rar://
要求有php-rar
扩展等。
天下熙熙,皆为利来;天下攘攘,皆为利往。