Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Post data using streams in PHP

I recently stumbled upon this ghost feature of PHP using which you can actually use streams in order to post data using a HTTP POST request.

Basically,

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.

PHP comes with streams functions out-of-the-box as they are part of PHP core. Here are all the stream functions that comes with PHP.

We’re specifically going to talk about one of these function called stream_context_create which can be used in combination with file_get_contents to send data using HTTP POST method.

file_get_contents with Streams

To actually send a HTTP POST request using file_get_contents, you’ll need to pass in a third parameter (which is a $context) to the file_get_contents function like so.

<?php

$postdata = [
    'var1' => 'some content',
    'var2' => 'doh'
];

$opts = [
    'http' => [
        'method'  => 'POST',
        'header'  => 'Content-type: application/json',
        'content' => $postdata
    ]
];

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

So, as you can see in the example, you can create a “stream context” using stream_context_create by passing various HTTP options as an array such as method, header, content etc. And now passing $context to file_get_contents will create a stream through which data can be sent over a HTTP POST request.

The same can be achieved for a FTP and SSL connection as well by replacing http with ftp and ssl in the context option respectively.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?