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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
StreamWrappers
Quoting the PHP Manual at Streams: Introduction:
You use Stream wrappers whenever you are opening URLs, FTP connection, etc with functions like
fopenorfile_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
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
would run the content from that webpage through gzip decompression.
Sockets
Quoting the PHP Manual at Sockets: Introduction:
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_contentscall in the example above, you’d need to do (example quoted from manual, you even need to do more actually)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: