Use the socket method in PHP to GET and POST data instances _ php instances

Source: Internet
Author: User
This article mainly introduces the use of socket GET and POST data instances in PHP. This article provides code instances for the GET and POST methods respectively. For more information, see 1. GET webpage content using PHP

The Code is as follows:


<? Php
Function socketGet ($ url, & $ ret)
{
$ UrlArr = parse_url ($ url );
$ Host = $ urlArr ['host'];
$ Port = isset ($ urlArr ['Port'])? $ UrlArr ['Port']: 80;
$ Path = isset ($ urlArr ['path'])? $ UrlArr ['path']: "/";
$ Fp = fsockopen ($ host, $ port, $ errno, $ errstr, 30 );
If (! $ Fp)
{
Echo "$ errstr ($ errno)
\ N ";
Return false;
}
Else
{
$ Out = "GET $ path HTTP/1.1 \ r \ n ";
$ Out. = "Host: $ host \ r \ n ";
$ Out. = "Connection: Close \ r \ n ";
$ Ret = "";
Fwrite ($ fp, $ out );
While (! Feof ($ fp ))
{
$ Ret. = fgets ($ fp, 128 );
}
Fclose ($ fp );
}
Return true;
}
?>

2. Use PHP to POST data to the page

The Code is as follows:


<? Php
Function socketPost ($ url, $ data, & $ ret)
{
$ UrlArr = parse_url ($ url );
$ Host = $ urlArr ['host'];
$ Port = isset ($ urlArr ['Port'])? $ UrlArr ['Port']: 80;
$ Path = isset ($ urlArr ['path'])? $ UrlArr ['path']: "/";
$ Fp = fsockopen ($ host, $ port, $ errno, $ errstr, 30 );
If (! $ Fp)
{
Echo "$ errstr ($ errno)
\ N ";
Return false;
}
Else
{
$ Out = "POST $ path HTTP/1.1 \ r \ n ";
$ Out. = "Host: $ host \ r \ n ";
$ Out. = "Content-Type: application/x-www-form-urlencoded \ r \ n ";
$ Out. = "Content-Length:". strlen ($ data). "\ r \ n ";
$ Out. = "Connection: Keep-Alive \ r \ n ";
$ Out. = $ data;
$ Ret = "";
Fwrite ($ fp, $ out );
While (! Feof ($ fp ))
{
$ Ret. = fgets ($ fp, 128 );
}
Fclose ($ fp );
}
Return true;
}
?>


If post reports an error, change Keep-Alive in $ out. = "Connection: Keep-Alive \ r \ n"; to Close.

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.