DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Big Data
  4. PHP streams for everything

PHP streams for everything

Giorgio Sironi user avatar by
Giorgio Sironi
·
Feb. 18, 13 · Interview
Like (0)
Save
Tweet
Share
10.09K Views

Join the DZone community and get the full member experience.

Join For Free

The stream extension of PHP is one of the batteries included in its packaging: a uniform interface to access many different types of data, relying on the common abstraction of a stream (not unlike, for example, Java's InputStream and OutputStream). It is not an object-oriented interface, but it is uniform across resource types, allowing reads and writes on files, processes, TCP sockets, and more; it's still polymorphism in action.

fopen() is more than you think

How do you read the contents of a file into a PHP variable? Sure, there are many shortcuts if you just want the whole file to be put into memory, such as file_get_contents(). However, assuming you want to lower your memory footprint and deal with arbitrarily large file, you can create a file descriptor and stream data in:

$fp = fopen("file.txt", "r");
$line = fgets($fp);

PHP interface in this case is similar to C's one. fgets() reads a line from a text file, but you have access to different methods, like fread() who reads an amount of bytes instead.

PHP extends the syntax of fopen() argument with a series of wrappers, that allow not only to access the filesystem but also other types of resources; for example, web pages:

$fp = fopen("http://www.example.com/file.txt", "r");
$line = fgets($fp);

Specialized functions that create streams

fopen() special syntax covers many cases, but sometimes creating a stream with specialized functions is simpler and clear, like in the case of TCP sockets:

$socket = fsockopen('example.com', 25);
$line = fgets($socket);

This is even more clear in the case of external processes, which may need many options to be specified such as environment variables and arguments. In this case, the created streams represent the standard input, standard output and standard error of the child process.

$process = proc_open('/bin/command', array(0 => 'r', 1 => 'w', 2 => 'w'), $pipes);
$line = fgets($pipes[0]);

More wrappers

However, why limit yourself to local processes? You may want to execute them on a remote machine via ssh (we're back to fopen()):

$fp = fopen('ssh2.exec://user:pass@example.com:22/usr/local/bin/somecmd');
$line = fgets($fp);

Or you can read from standard input:

$fp = fopen('php://stdin', 'r');
$line = fgets($fp);

Or the body of a PUT or POST request, since you don't want to keep that 50 MB zip archive into memory.

$fp = fopen('php://input', 'r');
$line = fgets($fp);

Or accessing a file insize that zip archive without expanding it:

$fp = fopen('zip://./foo.zip#bar.txt', 'r');
$line = fgets($fp);

Simulate a data stream

I learned from a colleague of mine a special kind of data stream to instantiate for testing, the data://* one; it allows you to specify a literal input in base64 format. With this stream you can avoid creating temporary files inside automated tests, which require bookkeeping and tearDown() methods:

// prints "I love PHP"
echo file_get_contents('data://text/plain;base64,SSBsb3ZlIFBIUAo=');

What works on file descriptors?

So we now know the type of resources that streams support: files, sockets, processes, and many more. But which functions can we run on the $fp file descriptors?

First of all, the siblings of fopen() are available for many operations. We have seen fgets() in action and we can add fread() and fwrite() to that; even fseek() works on many streams, sometimes only seeking forward in the contents.

Moreover, the stream extension provides a bunch of functions that work on any descriptor. You should only exclude from this list the stream_socket_*() which are specific to the management of TCP and UDP (client and server) sockets.

Not all of the operations are available on all streams, due to their constraints: for example, some allow only reads, not writing as is the case for HTTP; in our example, fopen()ing URLs works with GET requests and can only read the content of a resource, why you should use curl and other tools to make complex requests.

Still, even with these incompatibilities between streams, you only have to learn a single API to work on any kind of resource, along with the syntax to create that kind of stream. You can even create your own, userland stream wrapper in case it's not shipped with PHP.

PHP Data stream

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • REST vs. Messaging for Microservices
  • How to Submit a Post to DZone
  • Full Lifecycle API Management Is Dead
  • Application Architecture Design Principles

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: