Fsockopen
(PHP 3, PHP 4, PHP 5) Fsockopen - Open INTERNET OR UNIX DOMAIN Socket Connection
DescriptionResource
Fsockopen (String Target, int port [, int errno [, string errstr [, float timeout]])
Initiates a socket connection to the resource specified by target. PHP supports targets in the Internet and Unix domains as described in Appendix N. A list of supported transports can also be retrieved using stream_get_transports ().
Note: if You NEED TO SET A TIMEOUT for Reading / Writing Data over the socket, use stream_set_timeout (), as the timeout parameter to fsockopen () Only Applies While Connecting The Socket.
AS OF PHP 4.3.0, if You Have Compiled in OpenSSL Support, You May Prefix The Hostname with Either 'SSL: //' OR 'TLS: //' To Use An Ssl or TLS Client Connection over TCP / IP To Connect To The Remote Host.
Fsockopen () Returns A File Pointer Which May Be Used Together with the Other File Functions (Such as Fgets (), FGETSS (), FWRITE (), Fclose (), and Feof ()).
If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level connect () call. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect () call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.
Depending on the Environment, The Unix Domain or the Optional Connect Timeout May Not Be Available.
THE SOCKET WILL BY Default Be Opened in Blocking Mode. You can switch it to non-blocking mode by using stream_set_blocking ().
Example 1. Fsockopen () Example
PHP $ fp = fsockopen ("www.example.com", 80, $ errno, $ errstr, 30); if (! $ fp) {echo "$ Errstr ($ Errno)
/ 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);}?> the example below shows how to retrieve the Day and time from the udp service "daytime" (port 13) in Your Own Machine.
Example 2. USING UDP Connection
PHP $ fp = fsockopen ("udp: //127.0.0.1", $ errno, $ errstr); if (! $ fp) {echo "error: $ Errno - $ Errstr
/ n" Else {FWRITE ($ FP, "/ N"); Echo Fread ($ fp, 26); fclose ($ fp);}?>
Warning UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to / from the socket. The reason for this is because UDP is a "connectionless "Protocol, Which Means That The Operating System Does Not Try to Establish A Link for The Socket Until It Actually Needs to Send Or Receive Data.
Note: The IP address must be placed in square brackets when the IPv6 address of the specified number (for example, Fe80 :: 1). For example TCP: // [Fe80 :: 1]: 80.
Note: The Timeout Parameter Was Introducesd In PHP 3.0.9 and UDP Support Was Added in PHP 4.
See Also
Pfsockopen (),
stream_set_blocking (),
stream_set_timeout (),
FGETS (),
Fgetss (),
FWRITE (),
fclose (),
Feof (), and the
CURL EXTENSION.
Add a Note
User contributed notes
Fsockopen
MICHIEL AT PARSE DOT NL
25-OCT-2004 07:42
The Following Snippet Allows You to Retrieve The Title Oa Page.great for Rewriting Auto-Url Detectors to Display The Actual Title Rather Then http: // ...
/ n";} else {fputs ($ fp, "get /" $ down['path'].( URL ['Query']? '?'. $ URL ['Query']: '). "HTTP / 1.0 / R / NHOST:" $ URL [' Host ']. "/ R / N / R / n "); $ d = ''; while (! Feof ($ fp)) {$ d. = fgets ($ fp, 2048); if (preg_match ('~ head> | | Title> / s * (. *?) / s * title>)) ~ i ', $ d, $ m)) Break;} fclose ($ fp); return $ m [3];}}?> Elemental21 At Hotmail Dot COM
08-OCT-2004 10:23
Found this php class to use telnet from here: http: //cvs.adfinis.ch/cvs.php/phpStreamcast/telnet.class.phpThere's no docs and a lot of it's in french though so maybe it will help someone to have my Working code. this code is buy to telnet INTO A PIX AND Execute the "shun" command.//------telnet.class.php usage example --------- $ telnet = new telnet ///// by default you need to create a folder caled / log and give it the // Rights Your Webserver is Running. $ Telnet-> setlog (1, "mylog"); $ telnet- > set_host ("myhost.myplace.com"); // you need to set the prompt to what you know it. going to be, // Ten Call wait_prompt ... Which Waits for What You Just Set $ TELNET-> SET_PROMPT "Password:"); $ telnet-> connect (); $ telnet-> Wait_Prompt (); $ telnet-> write ("mypassword"); // Have to change the prompt ... in My Example this is the the / prompt this a pix will change to after loggin in. $ telnet-> set_prompt ("PIX>"); $ telnet-> Wait_Prompt (); $ telnet-> Write ("en"); $ telnet-> set_prompt ("password:"); $ telnet-> Wait_Prompt () $ Telnet-> Write ("enable_password"); // when Go Into Enable Mode in a PIX The Prompt Changes $ telnet-> set_prompt ("PIX #"); $ telnet-> Wait_Prompt (); $ telnet-> Write ("shun". $ shun_address); $ telnet-> Wait_Prompt (); $ telnet-> Write ("clear xlate"); $ telnet-> Wait_Prompt (); $ telnet->
Write ("Write Mem"); $ TELNET-> WAIT_PROMPT (); $ telnet-> Write ("exit"); $ telnet-> disconnect (); Mikebnospam At Xamo Dot COM
30-Sep-2004 07:17
Hey, why were my comments regarding fsockopen connection timeouts taken out? I'm sure they would have been very useful to other users.fsockopen (on FreeBSD and probably OpenBSD) will ignore the connection timeout parameter, and hang for several minutes if it can 'T Connect for a Variety of Reasons (NO DNS Resolve, Host Down, Extreme FireWall Setups). Use CURL INSTEAD (I SPENT DAYS ON this Issue)
AtayNet At ATAYNET DOT COM
21-aug-2004 04:01
Best Url Validator and Parser Function I have success write.;) Expression Must Be in a single line.function expLode_URL ($ URL) {$ TEMP ["Check"] = preg_match ("/ ^ (https {0, 1}): ((([A-ZA-Z0-9 -] {1,}) (: ([A-ZA-Z0-9 -] {0,})) @) {0,1}) (([A- Z0-9 -] {1,} /.) {0,1} ([A-Z0-9 -] {1,} /. [A-Z0-9 -] {1,}) (/. [a -Z0-9 -] {1,}) {0, 1}) (([0-9] {1,})) {0,1}) ((// ([[A-Z0-9- ] {1,} //) {0,}) (([AZ-0-9 -] {1,} (/. ([AZ-0-9 -] {1,}) {0,}) {0,1}) ((/? ([^ #?] {1,}) {0, 1}) (([^ #] {0,}) {0, 1})) { 0, 1} $ / ", $ URL, $ EXPLODE); if ($ TEMP [" Check "]) {$ TEMP [" Scheme "] = (! EMPTY ($ EXPLODE [1]))? $ EvdE [1 ]: ""; "$ TEMP [" User "] = (! EMPTY ($ evode [4]))? $ evode [4]:" "; $ TEMP [" pass "] = (! EMPLODE [6 ]))? $ evode [6]: ""; $ TEMP ["Host"] = (! EMPTY ($ evode [7]))? $ evode [7]: "; $ TEMP [" port "] = (! EMPTY ($ EXPLODE [13]))? $ evode [13]: "" $ TEMP ["Path"] = (! EMPTY ($ exPlode [15]))? $ evode [15]: " $ Temp ["BaseName"] = (! EMPTY ($ evode [17]))? $ evode [17]: "" $ TEMP ["EXTENSION"] = (! EMPTY ($ evtern [20]))? $ Explode [20]: ""; $ TEMP ["Query"] = (! EMPTY ($ EXPLODE [23]))? $ EXPLO DE [23]: "" $ TEMP ["fragment"] = (! EMPTY ($ evtern [26]))? $ evode [26]: "";} Return $ TEMP;} Bjorn (at) AHUSONLINE DOT COM
21-May-2004 07:50
Modified code for telnet to work with not-so-fast connections.The old version garbles the output and / or cuts the output before it is finished when output is above about 100 lines. Php # This is the difficult part, the Telnet Header $ header1 = chr (0xFF) .chr (0xfb) .chr (0x1f) .chr (0xf) .chr (0xfb) .chr (0x20) .chr (0xf) .chr (0xfb) .chr (0xfb) .chr (0x18) .chr (0x18) .chr (0x18) .chr (0x18) .chr (0x18) .chr (0x18) .chr (0x18) .chr (0xFF) .CHR (0xfb) .chr (0x27) .chr (0xff) .chr (0xFD) .chr (0x01) .chr (0x01) .chr (0xff) .chr (0xfb) .chr (0x03) .chr (0xf) .chr (0xFD). Chr (0x03) .chr (0xFF). Chr (0xfc) .chr (0x23) .chr (0xff) .chr (0xFF) .chr (0x24) .chr (0xfa) .chr (0xfa) .chr (0x1f) .chr (0x00) .chr (0x50) .chr (0x00) .chr (0x18) .chr (0xff) .chr (0xf0) .chr (0xFF) .chr (0xfa) .chr (0x20) .chr (0x00). Chr (0x38). Chr (0x34). Chr (0x30) .chr (0x30) .chr (0x30) .chr (0x2c) .chr (0x33) .chr (0x38) .chr (0x34) .chr (0x34) .chr (0x30) .chr (0x30) .chr (0xf) .chr (0xf0) .chr (0xf) .chr (0xfa) .chr (0x27) .chr (0x27) .chr (0x00) .chr (0x00) .chr (0xf0) .chr (0xFF). Chr (0x18). Chr (0x00) .chr (0x58) .chr (0x54) .chr (0x54) .chr (0x45) .chr (0x52) .chr (0x4d) .chr (0xff) .chr (0xF0); $ header2 = chr (0xFF) .chr (0xfc) .chr (0x01) .chr (0xff) .CHR (0xfc) .c .c .c HR (0x22) .chr (0xFF) .chr (0xfe) .chr (0x05) .chr (0xff) .chr (0xfc) .chr (0x21); # connecting $ fp = fsockopen ("127.0.0.0.1", 23) ; # sending the telnet headerfputs ($ fp, $ header1); Usleep (125000); FPUTS ($ FP, $ Header2); Usleep (125000); # loginfputs ($ FP, "User / R"); Usleep (125000) FPUTS ($ FP, "Users.Pass / R"); Usleep (125000); # root loocks nicefputs ($ fp, "su / r"); Usleep (125000); # Takes Some Time, We Had to Waitfputs $ fp, "root.pass / r"); # Some testsfputs ($ fp, "ifconfig / r"); FPUTS ($ FP, "Echo Year Telnet PHP Connect Works | Wall / R"); # we had to waitusleep (125000); # show the outputdo {$ output. = Fread ($ fp, 80); // read line by line, or at least small chunks $ stat =
Socket_get_status ($ fp);} while ($ stat ["unread_bytes"]); $ output = str_replace ("/ n", "
", $ output); Echo $ Output; fclose ($ fp);?> Alex At Renesource Dot LV
17-mar-2004 03:07
Set up SSL connection to server that requires client certificate: Convert client certificate from * .pfx (pkcs12) into * .pem with openssl (if needed):> openssl pkcs12 -in keys.pfx -out keys.pem PHP:
BIG_NICKY AT CLANSNET DOT DE
22-Feb-2004 11:55
And Here Is Some Working Code for a Normal Telnet Connection: # This is The Difficult Part, The Telnet Header $ Header1 = Chr (0xFF) .chr (0xfb) .chr (0x1f) .chr (0xFF) .chr (0xFF) .chr (0xfb). .CHR (0x20) .chr (0xFF). Chr (0xfb) .chr (0x18) .chr (0xff) .chr (0xfb) .chr (0x27) .chr (0xff) .chr (0x01) .chr (0x01) .chr (0x01) .chr (0x01) .Chr (0x01 .CHR (0xFF). Chr (0xFb) .chr (0x03) .chr (0xff) .chr (0xfd) .chr (0x03) .chr (0x03) .chr (0xff) .chr (0xfc) .chr (0x23) .chr (0xfc). ) .CHR (0x24) .chr (0xff) .chr (0xfa) .chr (0x1f) .chr (0x00) .chr (0x00) .chr (0x50) .chr (0x00) .chr (0x18) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .chr (0x00) .Chr (0x00) .chr ) .chr (0xF0) .chr (0xFF) .chr (0xFA) .chr (0x20) .chr (0x00) .chr (0x33) .chr (0x38) .chr (0x34) .chr (0x30) .chr (0x30 .CHR (0x33). Chr (0x38) .CHR (0x38) .CHR (0x34) .chr (0x30) .chr (0x30) .chr (0xff) .chr (0xf0) .chr (0xf0) .chr (0xf) .chr (0xfa) .chr ) .CHR (0x27) .chr (0x00) .chr (0xf) .chr (0xf0) .chr (0xf) .chr (0xfa) .chr (0x18) .chr (0x00) .chr (0x58) .chr (0x54) ). chr (0x45). Chr (0x52) .chr (0x4d) .chr (0xf) .chr (0xf0); $ header2 = chr (0xFF) .chr (0xfc) .chr (0x01) .chr (0xff). CHR (0xFC) .chr (0x22) .chr (0xFF) .chr (0xfe) .chr (0x05) .chr (0x05) .chr (0xff) .chr (0xfc) .chr (0x21); # connecting $ fp = PfsockOpen ("127.0. 0.1 ", 23); # sending The Telnet Headerfputs ($ FP, $ HEADER1); Sleep (1); FPUTS ($ FP, $ Header2); Sleep (1); # loginfputs ($ FP, "User / R"); Sleep (1); FPUTS $ fp, "users.pass / r"); Sleep (1); # root looks nicefputs ($ fp, "su / r"); Sleep (1); # Takes Some Time, We Had to Waitfputs ($ FP, "root.pass / r"); # Some Testsfputs ($ FP, "IFCONFIG / R"); FPUTS ($ FP, "Echo Year Telnet PHP Connect Works | Wall / R"); #WE Had to Waitsleep (1) ; # show the output # while (! Feof ($ fp)) {# $ output = fgets ($ fp, 128). "
/ n"; #} $ output = fread ($ fp, 128); $ Stat = Socket_get_status ($ fp); $ output. = FREAD ($ fp, $ stat ["unread_bytes"]); # uncomment these Lines to cut out the first line # $ output = expedition ("/ n", $ OTPUT );
#unset ($ OUTPUT ['0']); # $ output = Implode ("/ n", $ output); $ output = str_replace ("/ n", "
", $ output); Echo $ OTPUT ; fclose ($ fp);?> The header part is the difficult thing, this is testet on win and linux, its working fine, you can also use usleep on your linux system, and a work around function on win systems instead of sleep , if you want to speted up you script. I Hope i could help you! and sorry for my bad englishjack at jtr dot de
17-Feb-2004 06:05
Here is a function for testing a website / URI for availability:
14-Feb-2004 01:45
// This is a modification to the script I submitted below.// This script is an example of posting multiple files using // fsockopen.// The tricky part is making sure the HTTP headers and file boundaries are acceptable to the target webserver.// This script is for example purposes only and could / should be improved upon $ host = 'targethost';. $ port = 80; $ path = '/ test / socket / file_upload / receive_files.php'; // the File You want to upload $ file_Array [0] = "DingOboy.gif"; // the file $ file_array [1] = "dingoboy2.gif"; // the file $ file_array [2] = "Dingoboy3.gif"; / / the file $ content_type = "image / gif"; // the file mime type // $ content_type = "text / plain"; // echo "file_array [0]: $ file_array [0]
" SRAND (Double) microtime () * 1000000); $ boundary = "-------------------------". Substr (MD5 ( Rand (0,32000), 0,10); $ DATA = "- $ Boundary"; for ($ I = 0; $ I
25-JAN-2004 03:42
Header to declare cookie: Php / * [other headers] * / # Syntax => Cookie: name = value; name = value # Never finish with ';' $ header = "Cookie:. Name_cookie1 = value_cookie1; name_cookie2 = value_cookie2 / r / n ";> Header to create cookie: php / * [other headers] * / # syntax => set-cookie: Name = value [; path = path] [; expene = Domain_name] [; Secure] # DATE FORMAT: DAY, DD-MMM-YY HH: II: SS GMT # never finish with ';' $ header. = "Set-cookie: Name_cookie = value_cookie; Path = /; Friday, 13-JAN-03 12:00:00 GMT / R / N ";?> ROB At Robhulme Dot COM
24-Jan-2004 01:17
Just a note to everyone who is using fsockopen and fread / fgets for a HTTP connection.Unless you specify "Connection: Close" in your headers you will need to wait for the socket to time out before feof ($ streamPointer) to return true. This Has Wasted 2 Days of My Time, GRR! -ROB
ASALAMANCA AT Redcetus Dot COM
19-NOV-2003 03:27
This Is a Very Fast Program for test a formes. Php $ repeat = 100; // How much Times Repeat the test $ timeout = 100; // max time for stablish the profment $ size = 16 // Bytes Will Be Read (and Display). 0 for read all $ server = '64 .246.30.37 '; // ip address $ host =' www.foo.com '; // Domain Name $ target =' / poll /// specific program $ referer = 'http://www.test.com/'; // Referer $ port = 80; // setup an array of fields to get with threar the get string $ gets = array ( 'get_field_1' => 'somevalue', 'get_field_2' => 'somevalue'); // Setup an array of fields to post with then create the post string $ posts = array ( 'post_field_1' => 'somevalue ',' Post_field_2 '=>' somevalue '); // That's all. Now the program $ method = "get"; if (is_ARRAY ($ gets)) {$ getValues ='? '; Foreach ($ Gets as $ name => $ value) {$ getValues. = urlencode ($ name). "=". Urlencode ($ VA LuE). '&';} $ getValues = Substr ($ getValues, 0, -1);} else {$ getValues = ';} if (is_ARRAY ($ posts)) {foreach ($ posts as $ name => $ Value) {$ PostValues. = Urlencode ($ ". Urlencode ($ value). '&';} $ postvalues = Substr ($ PostValues, 0, -1); $ method =" post "; Else {$ PostValues = ';} $ request = "$ Method $ target $ getValues http / 1.1 / r / n"; $ request. = "Host: $ Host / R / N";
$ Request. = 'User-agent: mozilla / 5.0 (x11; u; linux i686; en-us; rv: 1.2.1)'; $ request. = "gecko / 20021204 / r / n"; $ request. = 'Accept: Text / XML, Application / XML, Application / XHTML XML,'; $ Request. = 'Text / HTML; Q = 0.9, Text / Plain; q = 0.8, Video / X-Mng, Image / PNG, '; $ Request. = "Image / jpeg, image / gif; q = 0.2, text / css, * / *; q = 0.1 / r / n"; $ request. = "Accept-language: EN-US, EN q = 0.50 / r / n "; $ request. =" Accept-encoding: gzip, deflate, compress; q= 0.9 / r / n "; $ request. =" accept-charSet: ISO-8859-1, UTF -8; Q = 0.66, *; q = 0.66 / r / n "; $ request. =" Keep-alive: 300 / r / n "; $ request. =" Connection: Keep-alive / r / n "; $ request. = "Referer: $ reres / r / n"; $ request. = "cache-control: max-age = 0 / r / n"; if ($ method == "post") {$ belnet = Strlen ($ PostValues); $ request. = "Content-type: Application / X-www-form-urlencoded / r / n"; $ request. = "Content-Length: $ LengHT / R / N"; $ request. = "/ r / n"; $ request. = $ PostValues;} for ($ I = 0; $ I ) {$ socket = fsockopen ($ Server, $ Port, $ Errno, $ Errstr, $ Errstr, $ Errstr, $ Errstr, $ Errstr Timeout; FPUTS ($ Socke T, $ request); if ($ subs> 0) {$ RET = FGETS ($ socket, $ size);} else {$ RET = '; while (! feof ($ socket)) {$ RET. = fgets ($ socket, 4096);}} fclose ($ socket); echo "
24-OCT-2003 03:30
Try this.use aut 821 WHEN HAVING Problems. Php $ handle = SMTP_CONNECT ($ SMTP_SERVER, 25, 30, 1, 1, 1); Echo SMTP_COMMAND ($ Handle, "Ehlo $ Domain / R / N ", 1, 1); Echo SMTP_COMMAND ($ Handle," Mail from: <$ from_mail> / r / n ", 1, 1); Echo SMTP_COMMAND ($ Handle," RCPT TO: <$ TO_MAIL> / R / n ", 1, 1); Echo SMTP_COMMAND ($ Handle," DATA / R / N ", 1, 1); Echo SMTP_COMMAND ($ Handle," $ Message / R / n. / r / n ", 1, 1 ); // don't do it like this - IT WILL HANG UP // Echo SMTP_COMMAND ($ Handle, "$ Message", 1, 1); // Echo SMTP_COMMAND ($ Handle, "/R/N./r / N ", 1, 1); Echo SMTP_COMMAND ($ Handle," Quit / R / N ", 1, 1); SMTP_Close ($ Handle); Function SMTP_CONNECT ($ Host, $ Port, $ TIMEOUT = 30, $ Echo_Command = False, $ Echo_response = false, $ nl2br = false) {$ errno = 0; $ Errstr = 0; if ($ Echo_Command) {IF ($ NL2BR) {Echo NL2BR ("Connecting to $ Host / R / N") Else {Echo "Connecting to $ Host / R / N";}} $ hand = fsockopen ($ Host, $ Port, $ Errno, $ ER RSTR, $ TIMEOUT; if (! $ hand) {if ($ echo_command) {if ($ nl2br) {Echo NL2BR ("Connection Failed / R / N");} else {echo "connection failed / r / n" }}}}}} {IF ($ nl2br) {Echo nl2br ("success / r / n");} else {echo "success / r / n";}}} $ response = fgets $ Handle, 1); $ BYTES_LEFT = Socket_get_status ($ Handle); if ($ BYTES_LEFT> 0) {$ response. = FREAD ($ handle, $ bytes_left ["unread_bytes"]);
} If ($ echo_response) {if ($ nl2br) {echo nl2br ($ response);} else {echo $ response;}} return $ handle;} function smtp_command ($ handle, $ command, $ echo_command = False, $ nl2br = False) {IF ($ nl2br) {Echo NL2BR ($ Command);} else {Echo $ Command;}} fputs ($ Handle, $ Command); $ response = fgets ($ handle, 1 ); $ BYTES_LEFT = Socket_get_status ($ Handle); IF ($, $ response. = FREAD ($ handle, $ bytes_left ["unread_bytes");} if ($ nl2br) {Return NL2BR ($ cyponse) } Else {return $ response;}} function smtp_close ($ hand) {fclose ($ hand);}?> Richardaburton At Hotmail Dot COM
19-OCT-2003 11:29
Improved HTTP / 1.1 chunked transfer-encoding example.The sample code given below by Jack does not function correctly when run against a recent version of Apache (I'm assuming that this did once work, but from the HTTP / 1.1 spec I can only Assume ITLY ON Luck). php $ header = "; $ response =" "; // connectif (! ($ request = fsockopen ('whatver.com', 80, $ errno, $ Errstr))) EXIT ($ Errstr); Else {socket_set_timeout ($ Request, 10); // Send Request Fwrite ($ Request, $ Post); // Get Header Do $ Header. = FREAD ($ Request, 1) WHILE (! preg_match ('/// r // n // r // n $ /', $ header); // check for chunked encoding if (preg_match ('/ transfert // - encoding: // s Chunked // r // n / ', $ head)) Do {$ BYTE = ""; $ chunk_size = ""; do {$ chunk_size. = $ byte; $ byte = fread ($ request, 1);} While ($ byte! = "// r"); // Till We match The Cr Fread ($ Request, 1); // Also Drop Off The lf $ chunk_size = hexdec ($ chunk_size); // Convert To Real Number $ response. = FREAD ($ Request, $ chunk_size); FREAD ($ Request, 2); // Ditch the crlf that trails the chunk} while ($ chunk_size); // Till We Reach the 0 Length Chunk (End Marker ELSE {// check for specified content lengthiff (preg_match ('/// - length: // s ([0-9] *) // r // n /', $ header, $ matches)) { $ response = FREAD ($ Request, $ matches [1]);} else {// NOT A NICE WAY TO DO IT (May Also Result In Extra CRLF Which Trails The Real Content ???) While (! Feof ($ Request )) $ response. = fread ($ Request, 4096);
}} // Close Connection Fclose ($ Request);} // do something useful with the responseprint ($ header); Print ($ response);?> Richard.pulstar At ig dot COM Dot Br
24-Sep-2003 02:24
To emulate a web browser with PHP using socket functions, there is a very good class to do this: http: //sourceforge.net/projects/snoopy/Some of its features: * easily fetch the contents of a web page * easily fetch the text from a web page (strip html tags) * easily fetch the the links from a web page (add a filter for "mailto:" links and you can easily fetch e-mail addresses) * supports proxy hosts * supports basic user. / pass authentication * supports setting user_agent, referer, cookies and header content * supports browser redirects, and controlled depth of redirects * expands fetched links to fully qualified URLs (default) * easily submit form data and retrieve the results * supports SSL and frames
Joe At Edwardsconsultants Dot COM
10-aug-2003 05:56
just a quick note for users attempting https and thinking they must resort to curl or alternate methods - you can use fsockopen, just read the docs closely basically they are saying to use 'ssl: //' for a HTTPS (SSL) web request. . So this 10, And Others; Even for That Paypal IPN - HOWEVER I Think It Would Be Best to Leave The Site and Deal With PayPal's Form: $ host = "somehost.somedomain.com"; $ port = 443; $ PATH = "/THE/url/path/file.php"; // or .dll, etc. For authnet, etc. // you will need to setup an array 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);} Sergiopaternoster At Tiscali Dot IT
31-jul-2003 01:49
If you want to connect via telnet, IT Could Be useful to set also the terminal type (some of the Terminal Type) $ IAC = chr (255); / * Interpret As Command: * / $ SB = CHR (250); / * Interpret As Subnegotiation * / $ SE = Chr (240); / * end sub negotiation * / $ telopt_ttype = chr (24); / * Terminal type * / $ telqual_is = chr (0); / * Option is ... * /// Sending Terminal Typefwrite ($ SOCK, $ IAC. $ SB. $ TELOPT_TTYPE. $ TELQUAL_IS. 'VT100'. $ Iac. $ SE); CIAOSERGIO PATERNOSTERJOHNYU At RevolutionHosting Dot Net
24-jul-2003 05:45
. It appears with PHP 4.3.2, on windows machines fsockopen is not able to use the ssl: // prefix even if you have the OpenSSL dll loaded in php.iniOn the otherhand, with PHP 4.5 CVS, it looks like SSL support For fsockopen is already Compiled in ... But it's missing the zip lib which i also need =
BRAGE (a t) jeffnappi (d. t) Commie
10-jul-2003 05:16
thought you guys may appreciate this function, allows you to pass an array of urls to download and does so simultaneously using non-blocking sockets, then returns the data in an array.// function connects to an array of URLS at the same time / / And return MultiHttp ($ urlarr) {$ sockets = array (); // socket array! $ urlinfo = array (); // info arr $ recdone = array (); $ backdata = array ( $ Errno = array (); $ Errstr = array (); for ($ x = 0; $ x 03-JUL-2003 09:53 I Also Needed A File Upload Via Fsockopen and Tried To Work with Chris Snyders Posting Above: ================================= POST / PATH / TO / SCRIPT. php HTTP / 1.0Host: example.comContent-type: multipart / form-data, boundary = AaB03xContent-Length: $ requestlen - AaB03xcontent-disposition: form-data; name = "field1" $ field1 - AaB03xcontent-disposition: form -data; name = "field2" $ field2 - AaB03xcontent-disposition: form-data; name = "userfile"; filename = "$ filename" Content-Type: $ mimetypeContent-Transfer-Encoding: binary $ binarydata - AaB03x- - ========================================================================= 1) Lines needed to end with / r / n (else the last character of the value was cropped) 2) I needed to remove Content-Type and Content-Transfer-Encoding from the binary "userfile" - else the uploaded file contained these strings and was Invalid! 3) The Receiving Script Couldn't Reference To The Variables $ FIELD1 Although Register_Globals Was Switch ON! Needed to Work with $ http_post_vars ['Field1'] and $ http_post_files ['userfile'] to get the value .ok, here's the script sending the header: $ f = fsockopen ($ Server, 80, $ Errno, $ Errstr, 30); fwrite ($ f, $ header); fclose ($ f); The receiving script is as easy :) The file was uploaded to $ HTTP_POST_FILES [ 'userfile'] [ 'tmp_name'] and the variables were named as mentioned above.Hope , IT Prevents Spending Another Afternoon To Figure :-) XbenseMhoun At T-Systems Dot fr25-jun-2003 05:48 To make A Telnet Connection With a Cisco Router: $ cfgserver = "192.168.0.10"; // ip of Your Router $ cfgport = 23; // Port, 22 IF SSH $ cfgtimeout = 10; $ USENet = FsockOpen ($ cfgserver, $ CFGPORT, & $ Errno, & $ Errstr, $ cfgtimeout; if (! $ usnet) {echo "connex"; exit ();} else {echo "connection / n Blazely At Removetoemail NetSpace Net Au 09-Jun-2003 12:55 Here's a quick function to establish a connection to a web server that will time out if the connection is lost after a user definable amount of time or if the server can not be reached.Also supports Basic authentication if a username / password is specified. Any improvements or criticisms, please email me! :-) Returns either a resource ID, an error code or 0 if the server can not be reached at all. Returns -1 in the event that something really wierd happens like a non-standard Http Response OR Something. Hope IT Helps Somene.cheers, Ben Blazed, $ USER = "", $ PATH, $ USER = "", $ pass = "", $ timeout = "30") {$ urlhandle = fsockopen $ Addr, $ Port, $ Errno, $ Errstr, $ TIMEOUT; if ($ urlhandle) {socket_set_timeout ($ urlhandle, $ timeout); if ($ PATH) {$ URLSTRING = "Get $ Path HTTP / 1.0 / R / NHOST: $ addr / r / nConnection: Keep-alive / r / number-agent: myurlgrabber / r / n "; if ($ user) $ urlstring. = "Authorization: Basic" .Base64_encode ("$ user: $ pass"). "/ r / n"; $ urlstring. = "/ r / n"; FPUTS ($ URLHANDLE, $ URLSTRING); $ Response = fgets ($ urlhandle); if (Substr_Count ($ Response, "200 OK")> 0) // Check The Status of the link {$ endheader = false; // strip initial header information while (! $ endheader) {f (FGETS ($ urlhandle) == " / r / n ") $ endheader = true;} returnome urlhandle; // all ok, return the file handle} else ing (Strlen ($ response) <15) // Cope with Wierd Non Standard response {fclose ($ URLHANDLE ); Return -1;} else // Cope with a standard error response {fclose ($ urlhandle); Return Substr ($ response, 9, 3);}} Return $ URLHANDLE;} else returno 0;} annettetruong at yahoo dot COM 28-May-2003 07:23 I need to use Paypal IPN and can not use fsockopen () or cURL. I'm trying the following as a workaround to using fsockopen () which creates a hidden form that is automatically submitted upon page load, with the final verification step from Paypal Caught In The IFAME. I Would Appreciate Comments on The Pitfalls to this method. About paypal ipn: http://www.paypal.com/cgi-bin/webscr? Cmd = p / xcl / r / ipn-introven outsidethanks , Annette. Php // Create One Additional Form Element Called 'CMD' $ HiddenForm = " / n"; // assemble page structure $ PageBody = "
"; FPUTS ($ UseNet, "TOTO / R / N"); FPUTS ($ USENET, "EN / R / N"); FPUTS ($ USENET, "Tutu / R / N"); FPUTS ($ USENET, "EXIT / R / N "); While (! Feof") {echo "." .Fgets ($ usnet, 128). "
/ n";}} the you will have: connected. ? ? ? ? .. User access :. TestXB> en. Password :. TestXB # exit. ipn results h2>"; // Look At Values Sent Via Post. // Add to Hidden Form in Same Order. Foreach ($ _POST AS $ Key => $ VALUE) {$ HiddenForm. = " / n"; // Display everything on the page for inspection. Echo $ key. ":" $ value. "
/ n";} // assemble pay PAL ipn hidden form. $ hiddenform = "
Verified 'or' Invalid '. If IT Shows // a Paypal Page Then Something Wright Wrong. $ Iframe = "
05-May-2003 01:49
You Can Know from Which Country Are Your visitors sending a query to ip-to-country online Tool Using code Below: ********************************* ************* $ IP = $ remote_addr; $ doc = "/ get-country /? ip =". $ ip. "& user = guest & pass = guest"; $ url = "ip -to-country.com "; $ fp = fsockopen ($ URL, 80, $ Errno, $ Errstr, 30); if (! $ fp) {echo" $ Errstr ($ Errno) / N "; Else {FPUTS ($ FP, "GET $ DOC HTTP / 1.0 / R / NHOST:" $ URL. "/ r / n / r / n"); while (! feof ($ fp)) {$ httpresult = FGETS ($ fp, 1024);} fclose ($ fp);} if (isset ($ httpresult)) {echo "ud. Est? Accediendo de: $ httpresult b>";} **** ******************************************* Note: i had to modify the code provided by ip-to- Country In Its Own Tools Section Because is buggy.
Csnyder At Chxo Dot COM
29-Mar-2003 11:04
NEED TO CREATE A POST REQUEST THAT THATION A FILE? I sprent this afternoon tryings like, and here is a template That Has Been successful for me: ============== ========== Post /Path/to/script.php http / 1.0host: eXample.comcontent-type: Multipart / Form-Data, Boundary = AAB03XCONTENTH: $ Requestlen - AAB03XCONTENT-DISPSITION: Form-data; name = "Field1" $ field1 - aab03xcontent-disposition: form-data; name = "Field2" $ field2 - aab03xcontent-disposition: form-data; name = "userfile"; filename = "$ filename" Content-Type: $ mimeTypeContent-Transfer-Encoding: binary $ binarydata - aab03x - =================================== Note That you have to to generate the Content-Length header after you generate the body of the request (from the first --AaB03x down, including the file data), so the thing to do in practice is to build the body first, get the strlen (), and THEN BUILD The Headers Onto The Front of the Body. See Rfc1867 - Form-based File Upload in Html (http://www.faqs.org/rfcs/rfc1867.html) for m Ore Info on the format of "Multipart / Form-Data" Posts. Good Luck! Admin at PHP DOT KZ
28-Mar-2003 09:19
[quote] Have Seen in Lot of Places PPL ASKING ON How To Post Data To Another Server Using A PHP Script ... so he is what is required to do this ... // create a string with all the posted data .. .foreach ($ http_post_vars as $ key => $ value) {$ value = urlencode; $ reg. = "& $ key = $ value";} ..... [/ quote] IT Is Better to Move '&' Sign To The End of String $ Req. = "$ Key = $ VALUE &"; NOSPAM AT PHPPATTERNS DOT COM
10-mar-2003 04:20
THE Second Half of The Sample Chapter (Chptr 2) from Pro PRO PRO PROP Web Services IS An in Depth Look At The Http Protocol And How To Build PHP Clients for it.http://www.rox.com/books/sample-chapters/ Samplechapter_1861008074.pdf [free]
Matthijs At Rohs Dot NL
18-Feb-2003 06:38
Here's a function that finds the Server Software of a server and returns it. The timeout is at 1 second, but I would prefer, if you use this function many times on a page, to set it lower. Php function get_server_software ($ Domain) {$ fp = fsockopen ($ Domain, 80, $ Errno, $ Errstr, 1); if (! $ fp) {Return ("");} else {fputs ($ fp, "HEAD / HTTP / 1.1 / R / NHOST: "$ domain." / r / n / r / n "); While (! Feof ($ fp)) {if (preg_match (" // bserver: / ", $ server = fgets ($ fp) , 256)) {fclose ($ fp); return (Substr ($ server, 8, -2));}} fclose ($ fp);}}?>
Sherif gayed
30-Jan-2003 02:00
Here ishind a proxy server: / ********************* * YOUR proxy server Address * / $ proxy = "192.168.10.1"; / * Your proxy server port * / $ port = 8080; / * the url you want to connect to * / $ url = "http://www.php.net/ "; $ fp = fsockopen ($ proxy, $ port); FPUTS ($ FP," Get $ URL HTTP / 1.0 / R / NHOST: $ proxy / r / n / r / n "); while (! feof ($) FP)) {$ LINE = FGETS ($ FP, 4000); Print ($ line);} fclose ($ fp); / ************ * End code ********* ******** / BART AT MediaWave Dot NL
06-JAN-2003 07:44
Here is a good article on some of the differences between http 1.0 and http 1.1.http://wireless.java.sun.com/midp/questions/chunking/
G Dot Bashi At NTLWorld Dot COM
04-JAN-2003 01:55
The Timeout Parameter Was Not Supported Under Windows Until PHP 4.3.0, Previously It Was fixed AT 30sec.
Dan at lovepond dot COM
18-DEC-2002 05:38
$ port = 4000; $ host = "localhost"; $ message = "test"; $ status = senddata ($ Host, $ Port, $ Message); Print "$ status"; Function Senddata ($ Host, $ Port) , $ message) {#takes in account servers that do not return EOF character # send data to server and get back input # function globals $ linenumber = "2"; #amount of lines to get rid of before we give input $ lineamount = "1"; #amount of lines to read off at We Give Input $ fp = fsockopen ("$ Host", $ Port, $ Errno, $ Errstr, 30); if (! $ Fp) {echo "$ Errstr ($ Errno (} else {for ($ i = 1; $ i <$ linenumber 1; $ i ) {FREAD ($ fp, 1); $ BYTES_LEFT = Socket_get_status ($ fp); if ($ BYTES_LEFT> 0) { Fread ($ FP, $ BYTES_LEFT [Unread_bytes]);}}}}} fputs ($ FP, "$ Message / R / N"); for ($ I = 1; $ 1; $ lineamount 1; $ i ) {$ status = FREAD ($ fp, 1); $ BYTES_LEFT = Socket_get_status ($ fp); if ($ BYTES_LEFT> 0) {$ status. = fread ($ fp, $ bottes_left [unread_bytes]);}} fclose ($ fp) } RETURN $ status;}?> here is some code to help out Abit more with the eof problem.i had a problem where I Needed to Strip Out So Many Lines of Server Input To Get Back Right Data I Wanted. Updateverran At Descent-Rangers Dot COM
17-OCT-2002 10:28
I Was tearing my hair out for a week trying to figure out how to do this.if you use fsockopen with a service tricen't Have An Eof, or you try break, php can hang completely.in My Case, I Was Trying to Write a Class What Talks To Get A List of People On The Chat Server. To Keep PHP from HANGING Due To The Above, I Discovered This: Class Kali_Utils { function games_list ($ kali_server_ip, $ kali_server_port) {$ result = array (); $ fp = fsockopen ($ kali_server_ip, $ kali_server_port, $ errno, $ error, 30); if (! $ fp) {$ result [ "errno" ] = $ Errno; $ Result ["Error"] = $ error;} else {fputs ($ fp, "kaliq"); $ header = fread ($ fp, 5); $ BYTES_LEFT = Socket_get_status ($ fp); if ($ BYTES_LEFT> 0) {$ Result ["results"] = FREAD ($ FP, $ BYTES_LEFT ["unread_bytes"]);} ELS E {$ Result ["] =" ";} fclose ($ fp);} Return $ Result;} }when i send the request packet, I get a response packet of length 5. Then i call socket_get_status () and Use the unread_bytes key from it to know how far tofread from the socket. Works very good.i've Only sale THIS on PHP 4.2.1 So far.iain at monitor-cho Dot UK
19-jul-2002 08:48
Here's how to send an email using SMTP. This includes rudimentary checking on server responses during the process of sending an email. Could be improved by more comprehensive processing of the result codes ... or going on to the next mail exchanger when you fail after "Function Another_mail ($ to, $ SUBJECT, $ Headers, $ Message) {// Could Get this from the php ini? $ from =" me@here.com "; list ($ me, $ Mydomain = Split ("@", $ from); // Now Look Up The Mail Exchangers for the Recipient List ($ USER, $ DOMAIN) = Split ("@", $ to, 2); if (GetMxrr ($ Domain, $ MX, $ Weight) == 0) Return False; // Try Them in Order of Lowest Weight First Array_multisort ($ MX, $ Weight); $ SUCCESS = 0; Foreach ($ MX AS $ Host) {//// Open An SMTP Connection $ Connection = Fsockopen ($ Host, 25, & $ Errno, & $ Errstr, 1); if (! $ Connection) Continue; $ RES = FGETS ($ Connection, 256); if (Substr ($ RESTR) 0, 3)! = "220") Break; // Introduce Ourslves FPUTS ($ Connection, "Helo $ MyDomain / N); $ RES = FGETS ($ Connection, 2 56); IF (Substr ($ RES, 0, 3)! = "250") Break; // envelope from FPUTS ($ Connection, "Mail from: $ from / n"); $ res = fgets ($ connection, 256); IF (Substr ($ RES, 0, 3)! = "250") Break; // Envelope to FPUTS ($ Connection, "RCPT to: $ TO / N"); $ RES = FGETS ($ Connection, 256); IF (Substr ($ RES, 0, 3)! = "250") Break; // The Message FPUTS ($ Connection, "DATA / N"); $ RES = FGETS ($ Connection, 256); if (Substr ($ RES, 0, 3)! = "354") Break;
// sent to :, from:, subject :, other headers, Blank Line, Message, And Finish // with a period on its Own Line. Fputs ($ Connection, "To: $ to / nfrom: $ from / nsubject: $ SUBJECT / N $ Headers / N / N $ Message / n. / n "); $ RES = FGETS ($ Connection, 256); IF (Substr ($ RES, 0, 3)! =" 250 ") Break; // Say Bye Bye FPUTS ($ Connection, "Quit / N"); $ RES = FGETS ($ Connection, 256); IF (Substr ($ RES, 0, 3)! = "221") Break; // IT WORKED! SO BREAK OUT OF THE LOOP Which Tries All The Mail Exchangers. $ success = 1; Break;} // debug for}} // debug foriff // Print $ SUCCESS? "Mail Sent": "Failure: $ RES / N "; if ($ connection) {if ($ success == 0) FPUTS ($ Connection," Quit / N "); fclose ($ connection);} Return $ success? true: false;} another_mail (" Recipient@some.domain, "My Subject", "X-MAILER: PHP Script / NX-Another-Header: WhatVer", "TEST Email Body./nnote if you actually put a period on a line / nby itself , the function will terminate prematurely./n/NYOU WILL GET A Partial Email Sent Though./N ");?> T DO T Hodder At Globalgold Dot Co Dot UK
26-jun-2002 11:52
You can post to a script that uses basic authentication if you create theheader like this and insert it into the relevant script above; // Build the header $ header = "POST /path/to/script.cgi HTTP / 1.0 / r / nAuthorization : Basic "; $ header. = Base64_encode (" $ usrname: $ password ")." / R / n "; $ header. =" Content-type: Application / X-www-form "; $ header. = "Content-length:". Strlen ($ request). "/ r / n"; $ header. = "Connection: Close / R / N / R / N";
INFO AT Free-Dev Dot COM
01-APR-2002 11:59
I'v Seen How Does A Get Request Works [Sample 1] and a Post Request Works Like That: Php $ fp = fsockopen ("192.168.0.3", 80); if ($ fp) {FPUTS ($ FP, "Post /localhost/test/p.php http / 1.1host: 192.168.0.3content-length: 7content-type: application / x-www-form-urlencodedConnection: Closea = 1 & B = 2"); while (! Feof ($) FP)) Echo fgets ($ fp, 128); fclose ($ fp);}?> Host: Must Be The Same as the Server Else The Post ISN'T ACCEPTEDCONTENT-LengHT: Is Thlenet of the line of the value of the value A = 1 & b = 2] a = 1 & b = 2 Values Are Writted Like a get but? at beginninging ... you can use post and get together with this line: post /localhost/test/p.php?val=3 http /1.1Have Fun! It's Just 4 Fun, Dont Try to Hack! Special Thanks Gnox: http://come.to/gnox
Philip At Cornado Dot COM
17-mar-2002 07:14
An example to send post data using fsockopen can be seen here: http://www.faqts.com/knowledge_base/view.phtml/AID/12039/fid/51
Arif Dot Budiman at no dot spam dot please
17-JAN-2002 12:43
This Example Queries Network Solutions Whois Database: $ Domain = "arifbudiman.net"; if ($ domain) <> "") {$ domain = trim ($ domain); $ fp = fsocken ("Whois.Networksolutions .com ", 43, $ errno, $ errstr, 30); if (! $ fp) {echo" $ Errstr ($ Errno) ";} else {FPUTS ($ FP," $ DOMAIN / R / N "); Print "
/ r / n"; while (! FeOf ($ fp)) {echo fread ($ fp, 128);} print " pre>"; fclose ($ fp);}}?>Info At TakeThisout Dot Ski-Info-Online Dot COM
08-JAN-2002 10:30
This is a "gotcha" that "got me" and discusses the careful use of HTTP / 1.1 over HTTP / 1.0 I had a script that suffered dreadful performance and return Hex values amongst the correct data. This was eventually traced to my inclusion of HTTP /1.1 in The Line Which Read: - Code (Watch Wrap) - $ Request = "Get $ Document". "?" "$ Query". "Http / 1.1 / r / n"; $ rouest. = " Host: $ myserver / r / n / r / n "; - CODE --BY Sending a http / 1.1 Request IT Declares That IT IS WILLING To 'Speak' http / 1.1, of course, but the it is available for http /1.1 that make it necessary to handle the socket differently from HTTP / 1.0 In the RFC 2616, Section 3.6 defines:. [...] All HTTP / 1.1 applications MUST be able to receive and decode the "chunked" transfer-coding, [...] This was the cause of the extraneous HEX values being displayed.Regards the loss of performance, this is also due to using HTTP / 1.1, which defaults to having keepalive on until you tell it to close the connection, or it Times out. Therefore The socket Was B eing kept open by the script.Simply changing the line in the script to HTTP / 1.0 completely fixed the problem.Speaking with one of the members in PHP-dev his words were: [Comment from Hartmut Holzgraefe] "I stumbled over the same ' CHUNKED 'PROBLEM NOT to LONG AGO As a rule of thumb: Never use http / 1.1 unless, claiming to be a http / 1.0 client is no problem.