Fsockopen analog http download file by socket

Source: Internet
Author: User
Tags php server

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.