Example of collecting webpage content using fsockopen in php

Source: Internet
Author: User

Fsockopen is a practical function in php. Next I will introduce the program that uses the fsockopen function to collect web pages. If you need it, please refer to it.

Usage
Int fsockopen (string hostname, int port, int [errno], string [errstr], int [timeout]);

A collection page instance

The Code is as follows: Copy code

<? Php
Function get_url ($ url, $ cookie = false)
{
$ Url = parse_url ($ url );
$ Query = $ url [path]. "?". $ Url [query];
Echo "Query:". $ query;
$ Fp = fsockopen ($ url [host], $ url [port]? $ Url [port]: 80, $ errno, $ errstr, 30 );
If (! $ Fp ){
Return false;
} Else {
$ Request = "GET $ query HTTP/1.1rn ";
$ Request. = "Host: $ url [host] rn ";
$ Request. = "Connection: Closern ";
If ($ cookie) $ request. = "Cookie: $ cookien ";
$ Request. = "rn ";
Fwrite ($ fp, $ request );
While (! @ Feof ($ fp )){
$ Result. = @ fgets ($ fp, 1024 );
}
Fclose ($ fp );
Return $ result;
}
}
// Obtain the html part of the url and remove the header
Function GetUrlHTML ($ url, $ cookie = false)
{
$ Rowdata = get_url ($ url, $ cookie );
If ($ rowdata)
{
$ Body = stristr ($ rowdata, "rnrn ");
$ Body = substr ($ body, 4, strlen ($ body ));
Return $ body;
}

Return false;
}
?>

Solution after being disabled

If fsockopen pfsockopen is disabled on the server, use other functions, such as stream_socket_client (). Note: The parameters of stream_socket_client () and fsockopen () are different.

Replace fsockopen (with stream_socket_client (, and then delete the port parameter "80" in the original fsockopen function and add it to $ host.

Example

The Code is as follows: Copy code

$ Fp = fsockopen ($ host, 80, $ errno, $ errstr, 30 );
Or
$ Fp = fsockopen ($ host, $ port, $ errno, $ errstr, $ connection_timeout );
After modification:
$ Fp = stream_socket_client ("tcp: //". $ host. "80", $ errno, $ errstr, 30 );
Or
$ Fp = stream_socket_client ("tcp: //". $ host. ":". $ port, $ errno, $ errstr, $ connection_timeout );


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.