I don't understand when should we use stream wrapper and socket. Can anyone tell me when should we use stream wrapper and socket in PHP?
Please give me some example regarding the same.
Quoting the PHP Manual at Streams: Introduction:
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)
You use Stream wrappers whenever you are opening URLs, FTP connection, etc with functions like fopen
or file_get_contents
. Stream wrappers have the benefit that you do not need to know much about the protocol (unless you write your own custom wrapper).
Since you you funnel all access through the regular file functionsDocs, you do not need to learn another API which is a benefit. You likely already used Stream Wrappers without noticing it, for instance, when you did
$pageContent = file_get_contents('http://example.com');
somewhere in your code. Another benefit of Stream Wrapper is that you can put filters in front and modify the stream with minimal effort, for instance
$unzipped = file_get_contents('compress.zlib://http://example.com');
would run the content from that webpage through gzip decompression.
Quoting the PHP Manual at Sockets: Introduction:
The socket extension implements a low-level interface to the socket communication functions based on the popular BSD sockets, providing the possibility to act as a socket server as well as a client.
Since PHP provides a number of Stream Wrappers out of the box and also has an API for almost everything, there is rarely any Use Case for using Sockets.
You use sockets when you need to implement at the protocol level to implement a client or a server for a certain protocol. This usually requires in-depth knowledge of the implemented protocol, for instance, to do the same as the file_get_contents
call in the example above, you'd need to do (example quoted from manual, you even need to do more actually)
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.example.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
As you can see, instead of just calling the URL and let the Stream Wrapper handle all the nitty gritty details you need to know how to construct an HTTP request and how to parse a HTTP response.
You might also find this tutorial about Socket Programming helpful:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With