PHP streams are a powerful and flexible way to handle data in PHP. They provide a consistent interface to interact with various data sources, such as files, network protocols, and even strings. Here's a broad overview of the main aspects of PHP streams:
$opts = [
'http' => [
'method' => "GET",
'header' => "Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
]
];
$context = stream_context_create($opts);
$file = file_get_contents('http://example.com', false, $context);
2. Filters - Filters can be attached to streams to process data as it's read from or written to the stream. -
Example: Reading a file and converting to uppercase:
$file = fopen('text.txt', 'r');
stream_filter_append($file, 'string.toupper');
while (!feof($file)) {
echo fgets($file);
}
fclose($file);
3. Wrappers - Wrappers abstract different types of data sources, making them accessible via a consistent stream interface. - Commonly used wrappers include `file://`, `http://`, `ftp://`, `php://input`, etc. -
Example: Reading from the PHP input stream:
$data = file_get_contents('php://input');
4. Stream Notifications - Allows you to monitor various events on streams like when data is being read, a connection is established, or metadata is being resolved. -
Example: Monitoring download progress:
function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
switch ($notification_code) {
case STREAM_NOTIFY_FILE_SIZE_IS:
echo "Found total file size: {$bytes_max} bytes\n";
break;
case STREAM_NOTIFY_PROGRESS:
echo "Downloaded {$bytes_transferred} bytes\n";
break;
}
}
$ctx = stream_context_create(null, ['notification' => 'stream_notification_callback']);
file_get_contents('http://example.com/large-file.zip', false, $ctx);
5. Custom Wrappers - You can even implement your own wrappers by defining a class that adheres to specific stream wrapper methods. -
Example: A basic custom wrapper (simplified):
class MyWrapper {
public $context;
public function stream_open($path, $mode, $options, &$opened_path) {
// Open stream logic
return true;
}
public function stream_read($count) {
// Read data logic
return 'data';
}
// ... other necessary wrapper methods
}
stream_wrapper_register('myproto', 'MyWrapper') or die('Failed to register protocol');
$fp = fopen('myproto://example/path', 'r');
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here