When we should we use stream wrapper and socket in PHP? -


i don't understand when should use stream wrapper , socket. can tell me when should use stream wrapper , socket in php?

please give me example regarding same.

streamwrappers

quoting php manual @ streams: introduction:

a wrapper additional code tells stream how handle specific protocols/encodings. example, http wrapper knows how translate url http/1.0 request file on remote server. there many wrappers built php default (see supported protocols , wrappers)

you use stream wrappers whenever opening urls, ftp connection, etc functions fopen or file_get_contents. stream wrappers have benefit not need know protocol (unless write own custom wrapper).

since funnel access through regular file functions­docs, not need learn api benefit. used stream wrappers without noticing it, instance, when did

$pagecontent = file_get_contents('http://example.com'); 

somewhere in code. benefit of stream wrapper can put filters in front , modify stream minimal effort, instance

$unzipped = file_get_contents('compress.zlib://http://example.com'); 

would run content webpage through gzip decompression.

sockets

quoting php manual @ sockets: introduction:

the socket extension implements low-level interface socket communication functions based on popular bsd sockets, providing possibility act socket server client.

since php provides number of stream wrappers out of box , has api everything, there use case using sockets.

you use sockets when need implement @ protocol level implement client or server protocol. requires in-depth knowledge of implemented protocol, instance, same file_get_contents call in example above, you'd need (example quoted manual, need 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 can see, instead of calling url , let stream wrapper handle nitty gritty details need know how construct http request , how parse http response.

you might find tutorial socket programming helpful:


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -