★ wanayoo — archive 1999 http://www.php.net/manual/function.fsockopen.phpNouvelle recherche | Portail wanayoo

PHP Home Page

Manual Table of Contents
Up to Network
Quick Reference
German version of this pageJapanese version of this pageItalian version of this pageFrench version of this pageHungarian version of this page
Network
* checkdnsrr
* closelog
* debugger_off
* debugger_on
* fsockopen
* gethostbyaddr
* gethostbyname
* gethostbynamel
* getmxrr
* getprotobyname
* getprotobynumber
* getservbyname
* getservbyport
* openlog
* pfsockopen
* socket_set_blocking
* syslog
* ip2long
* long2ip
Manual: fsockopen
View the source code for this pageSearch the site



Previous page
 debugger_on
 Updated
Sat, 12 Aug 2000
gethostbyaddr 
Next page


fsockopen

(PHP3 , PHP4 )

fsockopen --  Open Internet or Unix domain socket connection

Description

int fsockopen (string [udp://]hostname, int port [, int errno [, string errstr [, double timeout]]])

Initiates a stream connection in the Internet (AF_INET, using TCP or UDP) or Unix (AF_UNIX) domain. For the Internet domain, it will open a TCP socket connection to hostname on port port. For UDP connections, you need to explicitely specify the the protocol: udp://hostname. For the Unix domain, hostname will be used as the path to the socket, port must be set to 0 in this case. The optional timeout can be used to set a timeout in seconds for the connect system call.

Fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets(), fgetss(), fputs(), 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 on the system-level connect() call. If the returned 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 must 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 socket_set_blocking().

Example 1. Fsockopen() Example


$fp = fsockopen ("www.php.net", 80, &$errno, &$errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br>\n";
} else {
    fputs ($fp, "GET / HTTP/1.0\r\n\r\n");
    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",13, &$errno; &$errstr);
if (!fp) {
	echo "ERROR: $errno - $errstr<br>\n";
} else {
	fwrite($fp,"\n");
	echo fread($fp, 26);
	fclose($fp);
}
?>
	 
See also: pfsockopen()


User Contributed Notes: fsockopen


tkz@tkz.net
25-May-1999 07:18
This worked great on 3.07, but on 3.08 it seemed
to have problems until I raised the length on fget
to a larger number than the data length. Before
that it had an execution time out.



landen@frg.eur.nl
13-Jun-1999 02:02
On 3.0.9 you may have to set set_socket_blocking($fp, true) explicitly.



hiongun@kt.co.kr
31-Aug-1999 11:32
the example code seems to be wrong:
<pre>
fputs($fp,"GET / HTTP/1.0\n\n");
</pre>
should be re-written as:
<pre>
fputs($fp,"GET / HTTP/1.0\r\n\r\n");
</pre>
The protocol (HTTP) requires "CRLF", not
"LF" or "CR", even though there are abundant wrongly written examples published in the world.



silen@silen.net
21-Sep-1999 03:18
In 3.0.11, i can't repeatly call fsockopen(). Only the first is successful.
After that, the file descriptor will always has feof() true.



scott@mha.ca
12-Oct-1999 02:11
i am using 3.0.7 and it took me a while to realize that the last arg (timeout) does not exist. i kept getting a "Wrong parameter count" error (even though the same code worked on a different machine) so, after examining the changelog i tried it with just the first four args and it worked. this might seem obvious to people who are more familiar with this function, but it is probably worth noting for people using versions < 3.0.9.


pete.nelson@serversolved.com
18-Nov-1999 08:35
I can't find out how to pass a second line to fputs -
<pre>
fputs($fp, "GET / HTTP/1.0\n");
fputs($fp, "User-Agent: Nozilla/0.0 [en] (Linux)\n\n");
</pre>

The second 'fputs' never gets sent. Is it waiting for a response? Do I need to flush a buffer to get the second line to be sent?



milan@salajka.cz
24-Nov-1999 02:16
answer to previous question is:

<pre>
$agent = "Nozilla/0.0 [en] (Linux)";

$p = "GET / HTTP/1.0\r\n";
$p.= "User-Agent: $agent\r\n";
$p.= "Accept: */*\r\n";
$p.= "\r\n";

fputs ($fp,$p);
</pre>



nickl@mycomputer.com
10-Dec-1999 01:19
To repeatedly call fsockopen() in php
3.0.11, you need to do the following work-around since php's internal resource tracking is messed up:
<PRE>
if (PHP_VERSION == '3.0.11')
$s = fsockopen(&lt;parameters>);
$s = fsockopen(&lt;parameters>);
</PRE>



thenoog@hotmail.com
04-Jan-2000 09:02
Instead of a host name, can you pass an IP address somehow to fsockopen()?


kim_prog@post1.tele.dk
18-Jan-2000 04:59
Yes you can put in an ip number instead of a hostname ( fully qualified domain name )


zedek@matrix.com.br
08-Feb-2000 07:49
How to keep a connection, sending and receiving from it, like a telnet client?



dcassell@engage.com
10-Feb-2000 02:19
Use pfsockopen for persistent connections (i.e. telnet).


matt@ewtoo.org
23-Feb-2000 09:08
How do I open a socket to a web page as opposed to a web site?

eg.
www.php.net (works)
www.php.net/manual/add-note.php3 (fails with error 0)



evan@php.net
23-Feb-2000 07:23
Re: to the question above:

To open a connection to a website and retrieve the file name, use <PRE>fopen("http://some.site.com/html/page.html","r")</PRE>. Then use <PRE>fgets()</PRE> (or the like) to read in the page.



bhamon@qx.net
25-Feb-2000 10:01
To use this function to call a page on a certain site modify the fputs code as follows.

<pre>
$page = "somepage.html";
fputs($fp,"GET /$page HTTP/1.0\r\n\r\n");
</pre>



synec@i.am
27-Feb-2000 08:28
<pre>
$port = 8080;
$fp = fsockopen("localhost", $port, &$errno, &$errstr);

if($fp)
echo "$errstr ($errno)
\n";
else
{
fputs($fp,"GET /$command HTTP/1.0\r\n\r\n");

while(!feof($fp))
echo fgets($fp,128);
}
fclose($fp);
-----
Warning: Unable to find file identifier 0 in line "fputs", "feof", "fgets"

I don't know about Warning message.
help me.
</pre>



elliot@rightnowtech.com
28-Feb-2000 06:19
to: synec@i.am
your problem is:
<pre>if($fp)</pre>
should be
<pre>if(!$fp)</pre>
with the way your code is now. -elliot



m@1a.dk
29-Feb-2000 04:24
Can it really be true that fsockopen doesn't support higher ports like 27300? I just get a "No route to host (113)"


rdyer@cs.iastate.edu
08-Mar-2000 02:53
I'm trying to let users upload files to my web server and want to use php instead of cgi (which I've used in the past). Should I open a socket to read in the file?


kaspar.althaus@atsandwich.com
10-Mar-2000 07:52
when using pfsockopen how can you send the file pointer with ?get to the next page?


dan@fake.dk
19-Mar-2000 02:52
So the timeout was removed.. But what can i do if i need to control the timeout?


MStoner@psicorps.com
21-Mar-2000 05:02
I've ntoiced a lot of talk about the GET method. I was wondering if anyone had used POST.
<PRE>$tempstr = w3c -post -dest /$dest -form $fields / HTTP/1.0\r\n\r\n
fputs($fp, $tempstr);</PRE>

I'm waffling on whether it needs the w3c as a POST operation, but theres no documentation on this, only cross refrence between w3c and php.net, and I'm still looking for a way to check the status of the operation without setting up my own form handler.



morten2@online.no
29-Mar-2000 08:27
I miss a "timeout" option for fputs/fgets, I've been using the timeout successfully for my scripts, but I've found it to be only useful for avoiding slow and nonexisting servers.. When the server allows me to connect via fsockopen, but fails to respond on my queries, it often hangs completely.. So is there are will there be some optiong to control how long the socket shall wait for a response from the server it is connected to?


nishu@yamunda.com
06-Apr-2000 09:55
Hi
Is use of fsockopen is dependent on permissions? Like when using telnet connection to ISP computer??



bigmweb@altavista.com
14-Apr-2000 04:01
GET via HTTP/1.1 (for name-based virtual hosts)

<PRE>
function GetFromHost($host,$path) {
$fp = fsockopen($host,80);
fputs($fp,"GET $path HTTP/1.1\r\n");
fputs($fp,"Host: $host\r\n\r\n");
while(!feof($fp)){
echo fgets($fp,1024);
}
fclose($fp);
}
</PRE>

Mike



webmaster@netrpg.com
17-Apr-2000 11:14
Has there been any thought into adding UDP options to the network section of PHP?


meatgroup@dingoblue.net.au
24-Apr-2000 05:41
PHP4b4 was supposed to have added UDP support to fsockopen, but I can't find any documentation on it. Only this line in the release notes from Zeev:

- Added UDP support in fsockopen(). (Evan)



m@1a.dk
25-Apr-2000 11:40
Just looked into the source on the UDP matter. What I can see is that you have to write the host like: <pre>udp://host</pre> to use UDP


msauvain@edv-support.ch
04-May-2000 07:38
somebody try it out with ssh connections ?

could be very pretty !...

please informy .... thanks



no_junks_dil@hotmail.com
06-May-2000 12:53
Okay, all these are in respect to plain HTTP server.....
Now, how do I speak to an SSL-enabled server(https)?

_very urgent_



olli.holliday@redhotant.com
02-Jul-2000 06:28
"errorstr and errornum must be passed by reference"

if passing vars by ref. is deprecated (as php4 warns you) what's the preferred method of calling fsockopen().




lovetown@21cn.com
06-Jul-2000 02:28
I was wondering if anyone had used POST method ,why? how ?


keyan at operamail dot com
08-Jul-2000 04:00
For those interested, this is how I've used the post method. As far as I know, post is used for sending data to cgi scripts. For example, say you want to call a cgi-script that will add an entry to a guestbook:
<PRE>
// Data to pass to the cgi script
$name = 'John Doe';
$email = 'johndoe@domain.com';
$msg = 'Nice site, I love your animated gif collection!';

// Build the request string
$request = 'name=' . urlencode($name);
$request .= '&email=' . urlencode($email);
$request .= '&msg=' . urlencode($msg);

// Build the header
$header = "POST /guestbook/add.php3 HTTP/1.0\r\n";
$header .= "Content-type: application/x-www-form-urlencoded\r\n";
$header .= "Content-length: " . strlen($request) . "\r\n\r\n";

// Open the connection
$fp = fsockopen('www.domain.com', 80, &$err_num, &$err_msg, 30);
if ($fp)
{
// Send everything
fputs($fp, $header . $request);
// Get the response
while (!feof($fp))
$response .= fgets($fp, 128);
}
</PRE>
I think a browser would send something similar when submitting a form to a script.



keyan at operamail dot com
08-Jul-2000 04:19
This is a repost of the previous message, hopefully in a more readable form. (If only &lt;BR&gt; and &lt;P&gt; are going to be allowed, the comment about using &lt;PRE&gt; should be removed...grumble)



// Data to pass to the cgi script

$name = 'John Doe';

$email = 'johndoe@domain.com';

$msg = 'Nice site, I love your animated gif collection!';



// Build the request string

$request = 'name=' . urlencode($name);

$request .= '&email=' . urlencode($email);

$request .= '&msg=' . urlencode($msg);



// Build the header

$header = "POST /guestbook/add.php3 HTTP/1.0\r\n";

$header .= "Content-type: application/x-www-form-urlencoded\r\n";

$header .= "Content-length: " . strlen($request) . "\r\n\r\n";



// Open the connection

$fp = fsockopen('www.domain.com', 80, &$err_num, &$err_msg, 30);

if ($fp)

{

// Send everything

fputs($fp, $header . $request);

// Get the response

while (!feof($fp))

$response .= fgets($fp, 128);

}



I think a browser would send something similar when submitting a form to a script.



kevin@ntexpert.demon.co.uk
11-Jul-2000 10:59
Is it possible to use this to connect to
a news server on port 119?



zarjazz@barrysworld.com
11-Jul-2000 08:00
This function is missing a UDP option.


flec@flec.co.uk
12-Jul-2000 09:50
Actually, it's not - it's just not documented yet, (presumably?) because the UDP handling is still be being worked on. Use "udp://<hostname>" if you really need to use it in the hostname field.



-Steven Fletcher

[Barrysworld fan from ages past :-)]



dougtyrrell@hotmail.com
27-Jul-2000 06:28
Does this UDP solution really work? My firewall blocks fsockopen TCP scans but does not register fsockopen(udp://host, port) attempts.


sean@dsnet.net
29-Jul-2000 02:22
I'm writing an IRC bot and I'm using fsockopen(). For some reason It can only send certain amounts of data out at a time, in say 1000byte chunks then when more data comes in it sends the rest out like it's being buffered. If you know how to set the socket buffering so that it doesn't buffer or know how I can flush the socket buffer, please tell me. Thanks in advance.


dbora@consultant.com
01-Aug-2000 10:38
Some servers do not close connection

by default, so if you send just

fput($fp,"HEAD / HTTP/1.1\r\nHOST: dummy\r\n\r\n");

and trying to read response by

while(!feof($fp)) { $response .= fgets($fp,128); }
fclose($fp); }

it hangs (checked for IIS/4.0, for Apache - above code is OK)

use

fputs($fp,"HEAD $FilePath HTTP/1.1\r\n");

fputs($fp,"HOST: dummy\r\n");

fputs($fp,"Connection: close\r\n\r\n");




phreezing_phire@hotmail.com
03-Aug-2000 06:14
I have two questions, 1. how do i make something print out the number of times a word occurs on a text file, using all that $fp = fopen stuff, i know it's fgets, but i can't get it. then, 2. how do I make a form that sends an email to me WITHOUT opening a mail program? one that connects to a mail server and just sends it through the form. Please Email me if you can, Thanks,
Chris.



phreezing_phire@hotmail.com
04-Aug-2000 08:39
Okay I got the part about displaying the number of times a word occurs in a text file, I just need to know how to make a form that sends an email to me WITHOUT opening a mail program? one that connects to a mail server and just sends it through the form. Please Email me if you can, Chris.


armen@rfdigital.com
05-Aug-2000 08:40
Help?

I am also trying to do an fsockopen and fgets on a web page (domainname.com/page.htm) instead of the domainname.com alone.

When I place the "<pre>" statment, I get parse a error? I cant find any info about "<pre>" anywhere.

Thanks in advance.
Armen



 About Notes


Previous page
 debugger_on
 Updated
Sat, 12 Aug 2000
gethostbyaddr 
Next page





Who's responsible for this?
Top of this page

Site
Hosting:



Located in
United States
Elements of this website are subject to copyright.
Questions about installing or using PHP should be directed to one of the mailing lists.
Only questions about the website should be directed to webmaster@php.net.