What is stream in php

Understanding Streams in PHP

Streams are resources provided by PHP that we often use transparently, but which can also be very powerful tools. By learning how to harness their power, we can take our applications to a higher level.

The PHP manual has a great description of streams:

Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary locations within the stream.

Every stream has a implementation wrapper which has the additional code necessary to handle the specific protocol or encoding. PHP provides some built-in wrappers and we can easily create and register custom ones. We can even modify or enhance the behavior of wrappers using contexts and filters.

Stream Basics

A stream is referenced as :// . is the name of the wrapper, and will vary depending on the wrapper’s syntax.

The default wrapper is file:// which means we use a stream every time we access the filesystem. We can either write readfile(‘/path/to/somefile.txt’) for example or readfile(‘file:///path/to/somefile.txt’) and obtain the same result. If we instead use readfile(‘http://google.com/’) then we’re telling PHP to use the HTTP stream wrapper.

As I said before, PHP provides some built-in wrappers, protocols, and filters. To know which wrappers are installed on our machine we can use:

My installation outputs the following:

Array ( [0] => tcp [1] => udp [2] => unix [3] => udg [4] => ssl [5] => sslv3 [6] => sslv2 [7] => tls ) Array ( [0] => https [1] => ftps [2] => compress.zlib [3] => compress.bzip2 [4] => php [5] => file [6] => glob [7] => data [8] => http [9] => ftp [10] => zip [11] => phar ) Array ( [0] => zlib.* [1] => bzip2.* [2] => convert.iconv.* [3] => string.rot13 [4] => string.toupper [5] => string.tolower [6] => string.strip_tags [7] => convert.* [8] => consumed [9] => dechunk [10] => mcrypt.* [11] => mdecrypt.* )

A nice set, don’t you think?

In addition we can write or use third-party streams for Amazon S3, MS Excel, Google Storage, Dropbox and even Twitter.

The php:// Wrapper

PHP has its own wrapper to access the language’s I/O streams. There are the basic php://stdin , php://stdout , and php://stderr wrappers that map the default I/O resources, and we have php://input that is a read-only stream with the raw body of a POST request. This is handy when we’re dealing with remote services that put data payloads inside the body of a POST request.

Читайте также:  Html checkbox внешний вид

Let’s do a quick test using cURL:

curl -d "Hello World" -d "foo=bar&name=John" http://localhost/dev/streams/php_input.php

The result of a print_r($_POST) in the responding PHP script would be:

Array ( [foo] => bar [name] => John )

Notice that the first data pack isn’t accessible from the $_POST array. But if we use readfile(‘php://input’) instead we get:

Hello World&foo=bar&name=John

PHP 5.1 introduced the php://memory and php://temp stream wrappers which are used to read and write temporary data. As the names imply, the data is stored respectively in memory or in a temporary file managed by the underlying system.

There’s also php://filter , a meta-wrapper designed to apply filters when opening a stream with function like readfile() or file_get_contents() / stream_get_contents() .

The first example uses a filter to encode data written to disk while the second applies two cascading filters reading from a remote URL. The outcome can be from very basic to very powerful in our applications.

Stream Contexts

A context is a stream-specific set of parameters or options which can modify and enhance the behavior of our wrappers. A common use context is modifying the HTTP wrapper. This lets us avoid the use of cURL for simple network operations.

array( 'method'=>"POST", 'header'=> "Auth: SecretAuthTokenrn" . "Content-type: application/x-www-form-urlencodedrn" . "Content-length: " . strlen("Hello World"), 'content' => 'Hello World' ) ); $default = stream_context_get_default($opts); readfile('http://localhost/dev/streams/php_input.php');

First we define our options array, an array of arrays with the format $array[‘wrapper’][‘option_name’] (the available context options vary depending on the specific wrapper). Then we call stream_context_get_default() which returns the default context and accepts an optional array of options to apply. The readfile() statement uses these settings to fetch the content.

In the example, the content is sent inside the body of the request so the remote script will use php://input to read it. We can access the headers using apache_request_headers() and obtain:

Array ( [Host] => localhost [Auth] => SecretAuthToken [Content-type] => application/x-www-form-urlencoded [Content-length] => 11 )

We’ve modified the default context options, but we can create alternative contexts to be used separately as well.

Conclusion

How can we harness the power of streams in the real world? And where can we go from here? As we’ve seen, streams share some or all of the filesystem related functions, so the first use that comes to my mind is a series of virtual filesystem wrappers to use with PaaS providers like Heroku or AppFog that don’t have a real filesystem. With little or no effort we can port our apps from standard hosting services to these cloud services and enjoy the benefits. Also – and I’ll show in a follow-up article – we can build custom wrappers and filters for our applications that implementing custom file formats and encoding.

Share This Article

Vito Tardia (a.k.a. Ragman), is a web designer and full stack developer with 20+ years experience. He builds websites and applications in London, UK. Vito is also a skilled guitarist and music composer and enjoys writing music and jamming with local (hard) rock bands. In 2019 he started the BlueMelt instrumental guitar rock project.

Читайте также:  Java collection save to file

Источник

Introduction

Streams are the way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary location within the stream.

A wrapper is additional code which tells the stream how to handle specific protocols/encodings. For example, the http wrapper knows how to translate a URL into an HTTP/1.0 request for a file on a remote server. There are many wrappers built into PHP by default (See Supported Protocols and Wrappers), and additional, custom wrappers may be added either within a PHP script using stream_wrapper_register() , or directly from an extension. Because any variety of wrapper may be added to PHP, there is no set limit on what can be done with them. To access the list of currently registered wrappers, use stream_get_wrappers() .

  • scheme (string) — The name of the wrapper to be used. Examples include: file, http, https, ftp, ftps, compress.zlib, compress.bz2, and php. See Supported Protocols and Wrappers for a list of PHP built-in wrappers. If no wrapper is specified, the function default is used (typically file ://).
  • target — Depends on the wrapper used. For filesystem related streams this is typically a path and filename of the desired file. For network related streams this is typically a hostname, often with a path appended. Again, see Supported Protocols and Wrappers for a description of targets for built-in streams.

User Contributed Notes

  • Streams
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Stream Filters
    • Stream Contexts
    • Stream Errors
    • Examples
    • php_​user_​filter
    • streamWrapper
    • Stream Functions

    Источник

    Php streams

    Php streams

    Streams are the way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior.

    What are advantages of streams PHP?

    The stream wrappers’ main advantage is that data can be modified, changed, or deleted during the read/write process on the fly. PHP provides a few streaming filters. These include the string.

    What is PHP stream wrapper?

    A wrapper is additional code which tells the stream how to handle specific protocols/encodings. For example, the http wrapper knows how to translate a URL into an HTTP/1.0 request for a file on a remote server.

    How do PHP wrappers work?

    The PHP wrapper allows access to the languages’ own input and output streams, along with access to temporary memory and disk-backed file streams. To get access to the standard input stream, you can use php://stdin, which is read-only.

    What is a stream resource?

    StreamResource is a resource provided to the client directly by the application. Since: 3.0. Author: Vaadin Ltd.

    What does PHP output do?

    php://output is a write-only stream that allows you to write to the output buffer mechanism in the same way as print and echo.

    What is stream wrapper?

    A stream is a body of water that flows on Earth’s surface. The word stream is often used interchangeably with river, though rivers usually describe larger streams. Streams provide many benefits to humans.

    How do I filter in PHP?

    The filter_var() function both validate and sanitize data. The filter_var() function filters a single variable with a specified filter. It takes two pieces of data: The variable you want to check.

    Is PHP a software?

    The standard PHP interpreter, powered by the Zend Engine, is free software released under the PHP License. PHP has been widely ported and can be deployed on most web servers on a variety of operating systems and platforms.

    What are PHP protocols?

    The PHP HTTP(Hyper Text Transfer Protocol) functions allow us to handle the information which is sent to the browser by the web server. The purpose of the HTTP extension is to provide comfort and robust set of functionality for major applications.

    What protocols does PHP support?

    Supported Protocols and Wrappers ¶

    PHP comes with many built-in wrappers for various URL-style protocols for use with the filesystem functions such as fopen(), copy(), file_exists() and filesize(). In addition to these wrappers, it is possible to register custom wrappers using the stream_wrapper_register() function.

    What is the maximum PHP memory limit?

    Increasing the PHP memory limit

    The default memory limit is 256M and this is usually more than sufficient for most needs. If you need to raise this limit, you must create a phprc file.

    What is a resource in PHP?

    In PHP, Resource is a special data type that refers to any external resource. A resource variable acts as a reference to external source of data such as stream, file, database etc. PHP uses relevent functions to create these resources.

    What is stream context?

    A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream. Contexts are created using stream_context_create() and can be passed to most filesystem related stream creation functions (i.e. fopen(), file(), file_get_contents(), etc. ).

    What is File_get_contents?

    The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.

    Search Do not index some parts of HTML

    Noindex

    How do I stop Google from indexing certain pages?How do you add no index in HTML?How do I stop pages from indexing?What is noindex nofollow?Should I .

    How to add anti csrf token to the forms (No Anti-CSRF tokens were found in a HTML submission form.)

    Csrf

    How do I get my CSRF token?What is absence of anti CSRF tokens?Where do I implement CSRF token?What is CSRF token full form?Why is CSRF difficult to .

    Logo

    How do you check if a logo is already used?How do you check if a logo has been copyrighted?How can I test my logo?How do I make sure my logo is not p.

    Источник

Оцените статью