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.