When using phpsocket, We need to enable socket extension first. We can use phpinfo (); check whether socket extension is enabled; otherwise, in php. ini is enabled. If it is not enabled, we can refer to the following method to set the socket extension when using php socket. We can use phpinfo (); check whether the socket extension is enabled. Otherwise. ini is enabled. If it is not enabled, we can refer to the following method to set
Script ec (2); script
Socket Extension in windows
In windows, you can directly modify the php. ini file to remove the semicolon before extension = php_sockets.dll and restart it.
Install socket extension for PHP in linux
| The Code is as follows: |
|
|
# Cd/home/php5.2.1/ext/sockets
#/Server/php/bin/phpize
#./Configure -- prefix =/usr/local/php/lib -- with-php-config =/server/php/bin/php-config -- enable-sockets
# Make
# Make install
Modify the/usr/local/php/etc/php. ini file.
# Extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/" (php5.4 or above without the extension path)
Extension = sockets. so |
Restart apache
Okay. Let's get started.
| The Code is as follows: |
|
|
// POST submission
Function socketPost ($ url, $ data ){
$ PostStr = '';
$ PostLen = '';
$ Out = '';
// Resolve the domain
$ UrlInfo = parse_url ($ url );
$ Host = $ urlInfo ['host'];
If (! Isset ($ urlInfo ['query']) $ urlInfo ['query'] = '';
$ Path = $ urlInfo ['path']. '? '. $ UrlInfo ['query'];
// Organize data
Foreach ($ data as $ key => $ value ){
$ PostStr. = $ key. '='. rawurlencode ($ value). '&'; # encode the post value. Otherwise, an interruption occurs.
}
$ PostStr = trim ($ postStr ,"&");
$ PostLen = strlen ($ postStr );
$ Fp = fsockopen ($ host, 80, $ errno, $ errstr, 3 );
If ($ fp ){
$ Out. = "POST". $ path. "HTTP/1.0 \ r \ n ";
$ Out. = "Host:". $ host. "\ r \ n ";
$ Out. = "Content-type: application/x-www-form-urlencoded \ r \ n ";
$ Out. = "Content-Length:". $ postLen. "\ r \ n"; # It is best to add Connection: close
$ Out. = "\ r \ n ";
$ Out. = $ postStr;
Fwrite ($ fp, $ out );
Fclose ($ fp );
}
} |
Usage
| The Code is as follows: |
|
|
SocketPost ("submitted address", array ("username" => "here is the post username", "password" => 321312312 ));
Function socketGet ($ url ){
$ UrlInfo = parse_url ($ url );
$ Host = $ urlInfo ['host'];
If (! Isset ($ urlInfo ['query']) $ urlInfo ['query'] = '';
$ Path = $ urlInfo ['path']. '? '. $ UrlInfo ['query'];
$ Fp = fsockopen ($ host, 80, $ errno, $ errstr, 3 );
If ($ fp ){
// Call the module to capture information
$ Out = "GET {$ path}/HTTP/1.1 \ r \ n ";
$ Out. = "Host: {$ host} \ r \ n ";
$ Out. = "Connection: Close \ r \ n ";
Fwrite ($ fp, $ out );
Fclose ($ fp );
}
} |
Usage: socketGet ("url ");
Work needs to be encapsulated to facilitate calls by colleagues.