Home > Article > Backend Development > How to use the fsockopen function in PHP?
The function of fsockopen function in PHP is to open a network connection or a Unix socket connection. Its syntax is "fsockopen($hostname)", and the return value is a file handle, which can later be used by other file types. function call.
Simple example
<?php $fp = fsockopen("www.example.com", 80, $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)<br />\n"; } else { $out = "GET / HTTP/1.1\r\n"; $out .= "Host: www.example.com\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); while (!feof($fp)) { echo fgets($fp, 128); } fclose($fp); } ?>
Using UDP connection
<?php $fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr); if (!$fp) { echo "ERROR: $errno - $errstr<br />\n"; } else { fwrite($fp, "\n"); echo fread($fp, 26); fclose($fp); } ?>
Usage example
<?php $host = "something.example.com"; $port = 443; $path = "/the/url/path/file.php"; //or .dll, etc. for authnet, etc. //you will need to setup an array of fields to post with //then create the post string $formdata = array ( "x_field" => "somevalue"); //build the post string foreach($formdata AS $key => $val){ $poststring .= urlencode($key) . "=" . urlencode($val) . "&"; } // strip off trailing ampersand $poststring = substr($poststring, 0, -1); $fp = fsockopen("ssl://".$host, $port, $errno, $errstr, $timeout = 30); if(!$fp){ //error tell us echo "$errstr ($errno)\n"; }else{ //send the server request fputs($fp, "POST $path HTTP/1.1\r\n"); fputs($fp, "Host: $host\r\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: ".strlen($poststring)."\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $poststring . "\r\n\r\n"); //loop through the response from the server while(!feof($fp)) { echo fgets($fp, 4096); } //close fp - we are done with it fclose($fp); }
Recommended tutorial: "PHP"
The above is the detailed content of How to use the fsockopen function in PHP?. For more information, please follow other related articles on the PHP Chinese website!