Fsockopen is very powerful, such as the previous analog HTTP access, analog post/get request, what, here is another example, is to download things. For example, download http://www.nowamagic.net//librarys/webapp/Snow.zip this file, with the following program can be implemented:
#Socket emulation HTTP protocol transfer file#HTTP is the application-layer protocol using port#$hostname= ' Www.nowamagic.net ';$port= ' 80 ';#Establish a connection$fp=Fsockopen($hostname,$port,$errno,$errstr);//set_socket_blocking ($fp, false);//stream_set_blocking ($fp, 0);stream_set_blocking($fp,true); if(!$fp){ Echo"$errno:$errstr<br/> ";}Else{ #send an HTTP request information header $request _header= "Get/librarys/webapp/snow.zip http/1.1\n"; #Start line #header Field $request _header. = "Host:$hostname\ n "; #and then a carriage return. Line break indicates end of header information $request _header. = "\ n"; #send request to server fputs($fp,$request _header); #Accept Response $fp 2=fopen(' Snow.zip ', ' W '); while(!feof($fp)) { $line=fputs($fp 2,fgets($fp, 128)); //echo $line; } #Close fclose($fp 2); fclose($fp);}
Execute the program and you will find that the file you need to download will appear in the sibling directory of the program file.
This is essentially the Socket analog HTTP protocol transfer file. Also pay attention to the PHP time-out limit, here set my PHP server timeout is unlimited to download correctly, or may download the PHP program will stop.
At the same time, the use of set_socket_blocking and stream_set_blocking also need a little attention, Google will be able to understand, here no longer repeat.
Fsockopen analog http download file by socket