PHP Stream
Handle data streams and file operations
🌊 What are PHP Streams?
Streams provide a unified way to work with files, network connections, and data compression. They allow you to read and write data efficiently using a consistent interface.
<?php
// Open a stream to read a file
$stream = fopen('data.txt', 'r');
$content = fread($stream, 1024);
fclose($stream);
?>
Key Stream Functions
Open Stream
Open file or URL stream
fopen($filename, $mode);
Read Stream
Read data from stream
fread($stream, $length);
Write Stream
Write data to stream
fwrite($stream, $data);
Close Stream
Close stream connection
fclose($stream);
🔹 Reading Files with Streams
Open and read file content using stream functions. Streams provide fine-grained control over how you read data, allowing you to process large files efficiently.
<?php
// Open file for reading
$file = fopen('example.txt', 'r');
if ($file) {
// Read entire file
$content = fread($file, filesize('example.txt'));
echo "File content: " . $content;
// Close the stream
fclose($file);
} else {
echo "Unable to open file";
}
// Alternative: Read line by line
$file = fopen('example.txt', 'r');
while (($line = fgets($file)) !== false) {
echo $line . "<br>";
}
fclose($file);
?>
Output:
File content: Hello from the file!
Hello from the file!
🔹 Writing to Files
Create or modify files using stream write operations. Different modes control whether you append, overwrite, or create new files when writing data.
<?php
// Open file for writing (creates if doesn't exist)
$file = fopen('output.txt', 'w');
if ($file) {
$text = "Hello, World!\n";
$text .= "This is a new line.";
fwrite($file, $text);
fclose($file);
echo "File written successfully";
} else {
echo "Unable to open file for writing";
}
// Append to existing file
$file = fopen('output.txt', 'a');
fwrite($file, "\nAppended text");
fclose($file);
?>
Output:
File written successfully
🔹 Stream Context Options
Configure stream behavior using context options. This allows you to set HTTP headers, timeouts, and other parameters when working with remote resources.
<?php
// Create stream context with options
$options = array(
'http' => array(
'method' => 'GET',
'header' => 'User-Agent: PHP Script\r\n',
'timeout' => 10
)
);
$context = stream_context_create($options);
// Use context when opening stream
$url = 'https://api.example.com/data';
$response = file_get_contents($url, false, $context);
if ($response !== false) {
echo "Data fetched successfully";
} else {
echo "Failed to fetch data";
}
?>
Output:
Data fetched successfully
🔹 Stream Filters
Apply filters to transform data as it passes through a stream. Filters can compress, encrypt, or convert data on-the-fly without loading everything into memory.
<?php
// Open file stream
$file = fopen('data.txt', 'r');
// Apply uppercase filter
stream_filter_append($file, 'string.toupper');
// Read filtered content
$content = fread($file, 1024);
echo "Filtered content: " . $content;
fclose($file);
// Example with compression filter
$compressed = fopen('compressed.gz', 'w');
stream_filter_append($compressed, 'zlib.deflate');
fwrite($compressed, "This text will be compressed");
fclose($compressed);
echo "<br>File compressed successfully";
?>
Output:
Filtered content: HELLO WORLD
File compressed successfully
🔹 Stream Wrappers
Access different types of resources using stream wrappers. PHP supports file://, http://, ftp://, and other protocols through a unified stream interface.
<?php
// File wrapper (default)
$local = fopen('file://path/to/file.txt', 'r');
// HTTP wrapper
$web = fopen('http://example.com/data.txt', 'r');
if ($web) {
$content = fread($web, 1024);
echo "Web content: " . substr($content, 0, 50) . "...";
fclose($web);
}
// PHP input stream (for POST data)
$input = file_get_contents('php://input');
echo "<br>Received input: " . $input;
// Memory stream
$memory = fopen('php://memory', 'r+');
fwrite($memory, 'Temporary data');
rewind($memory);
echo "<br>Memory: " . fread($memory, 1024);
fclose($memory);
?>
Output:
Web content: <!DOCTYPE html><html><head><title>Example Domain</title>...
Received input:
Memory: Temporary data
🔹 Checking Stream Status
Monitor stream state and position using status functions. These help you determine if you've reached the end of a file or check the current read/write position.
<?php
$file = fopen('example.txt', 'r');
// Check if end of file
if (feof($file)) {
echo "End of file reached<br>";
} else {
echo "More data available<br>";
}
// Get current position
$position = ftell($file);
echo "Current position: " . $position . "<br>";
// Move to position 10
fseek($file, 10);
echo "New position: " . ftell($file) . "<br>";
// Rewind to beginning
rewind($file);
echo "After rewind: " . ftell($file);
fclose($file);
?>
Output:
More data available
Current position: 0
New position: 10
After rewind: 0
🔹 Stream Metadata
Retrieve information about streams and files. Metadata includes file size, modification time, permissions, and other properties useful for file management.
<?php
$file = fopen('example.txt', 'r');
// Get stream metadata
$meta = stream_get_meta_data($file);
echo "Stream type: " . $meta['stream_type'] . "<br>";
echo "Mode: " . $meta['mode'] . "<br>";
echo "Seekable: " . ($meta['seekable'] ? 'Yes' : 'No') . "<br>";
fclose($file);
// Get file stats
$stats = stat('example.txt');
echo "File size: " . $stats['size'] . " bytes<br>";
echo "Last modified: " . date('Y-m-d H:i:s', $stats['mtime']);
?>
Output:
Stream type: STDIO
Mode: r
Seekable: Yes
File size: 1024 bytes
Last modified: 2024-03-15 10:30:45