Trong PHP, "giao thức giả" (pseudo-protocols) là cơ chế đặc biệt không liên quan đến truyền tải mạng truyền thống, dùng để truy cập các tính năng hoặc tài nguyên nội bộ của PHP. Các giao thức này thường bắt đầu bằng "php://", hỗ trợ thao tác với luồng dữ liệu, bộ nhớ, và quản lý tiến trình.
Luồng Nhập/Xuất Cơ Bản
php://input: Luồng đọc-only để lấy dữ liệu POST gốc từ request HTTP. Có thể đọc nhiều lần mà không ảnh hưởng nội dung.
$input = fopen('php://input', 'r');
$postData = stream_get_contents($input);
fclose($input);
php://output: Luồng ghi trực tiếp đến đầu ra chuẩn (thường là trình duyệt).
$stdout = fopen('php://output', 'w');
fwrite($stdout, 'Dữ liệu xuất ra trực tiếp');
fclose($stdout);
Bộ Nhớ Tạm Thời
php://memory: Dùng RAM để lưu trữ dữ liệu tạm thời. Dữ liệu biến mất khi đóng luồng.
php://temp: Tương tự memory, nhưng tự động chuyển sang đĩa khi vượt 2MB.
$temp = fopen('php://memory', 'w+');
fwrite($temp, 'Dữ liệu tạm');
rewind($temp);
echo fread($temp, 1024);
fclose($temp);
Tiêu Chuẩn Đầu Vào/Đầu Ra
php://stdin: Đọc dữ liệu từ stdin (dòng lệnh hoặc thiết bị ngoại vi).
$stdin = fopen('php://stdin', 'r');
$name = trim(fgets($stdin));
echo "Xin chào $name!";
fclose($stdin);
php://stdout: Ghi dữ liệu đến stdout (terminal hoặc file).
fwrite(fopen('php://stdout', 'w'), 'Thông báo chuẩn');
php://stderr: Ghi thông báo lỗi riêng biệt với stdout.
fwrite(fopen('php://stderr', 'w'), 'Lỗi kết nối cơ sở dữ liệu');
Xử lý tiến trình con với proc_open
Ví dụ chạy lệnh shell và thu thập output/error:
$cmd = 'ls -la';
$desc = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w']
];
$pipes = [];
$process = proc_open($cmd, $desc, $pipes);
if (!$process) die('Lỗi khởi tạo tiến trình');
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$exitCode = proc_close($process);
echo "Kết quả: $output\n";
echo "Mã thoát: $exitCode";
Các Giao Thức Hệ Thống Phổ Biến
file://: Truy cập tập tin cục bộ.
$file = fopen('file:///tmp/config.ini', 'r');
http:///https://: Kết nối HTTP(S) server.
$http = fopen('https://api.example.com/data', 'r');
ftp:///ftps://: Tải/tải lên file qua FTP.
$ftp = fopen('ftp://user:pass@server.com/file.zip', 'r');
zlib://: Xử lý file nén gzip.
$gz = fopen('compress.zlib://data.gz', 'r');
data://: Dữ liệu inline base64 (RFC 2397).
$data = fopen('data://text/plain;base64,SGVsbG8gVmlldG5hbQ==', 'r');
glob://: Tìm file theo mẫu wildcard.
foreach (glob('glob://*.php') as $file) echo $file;
phar://: Truy cập PHP Archive.
$phar = fopen('phar://app.phar/config.yaml', 'r');
ssh2://: Kết nối SSH an toàn.
$ssh = fopen('ssh2://root@192.168.1.100:/etc/hosts', 'r');
rar://: Xử lý file RAR.
$rar = fopen('rar://archive.rar/report.pdf', 'r');
ogg://: Xử lý luồng âm thanh Ogg.
$ogg = fopen('ogg://audio.ogg', 'r');
expect://: Tương tác với lệnh dòng lệnh.
$expect = fopen('expect://bash', 'r');