Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fsockopen

Status
Not open for further replies.

tweenerz

Programmer
Mar 25, 2002
202
US
I am forced to use fsockopen as opposed to fopen in my script. This seems like an easy operation, but I cant figure out how to do it.

I can connect fine to the server by using the domain name. But I can't figure out how to access a page further down the path.

For example:
Code:
  fsockopen('[URL unfurl="true"]www.example.com',80,$errno,$err,30)[/URL]

The above works fine.

But how to I get the a file located in ? I can't just add it to the fsockopen argument, because it just wants a domain or ip. So how do I access a page othe than the root?

Thanks in advance.
 
Use FGETS to access individual pages, the fsockopen is analogous to the mysql_connect function in that is opens a resource stream

Bastien

Cat, the other other white meat
 
fsockopen() just opens the connection and hands you a resource handle. After that you have to talk to the server using that handle and send HTTP requests - you are probably going to use a GET request.
The PHP documentation has the following example:
Code:
<?php
$fp = fsockopen("[URL unfurl="true"]www.example.com",[/URL] 80, $errno, $errstr, 30);
if (!$fp) {
   echo "$errstr ($errno)<br />\n";
} else {
   $out = "GET / HTTP/1.1\r\n";
   $out .= "Host: [URL unfurl="true"]www.example.com\r\n";[/URL]
   $out .= "Connection: Close\r\n\r\n";

   fwrite($fp, $out);
   while (!feof($fp)) {
       echo fgets($fp, 128);
   }
   fclose($fp);
}
?>

The $out variable holds the constructed HTTP GET request that needs to be sent before you can use fgets() to retrieve the response.
 
Thanks.

This led me to the answer I was looking for. I needed to figure out how/where to specify the path to the file I want.

The answer was in the
Code:
$out = "GET / HTTP/1.1\r\n";
line. The lone '/' is the path. I didn't realize that. So for my example above I would specify
Code:
$out = "GET /dir/file.php HTTP/1.1\r\n";
instead.

(I posted this for future searches)
 
Yes, the '/' resolves to the document root of the server you accessed.
Just as a note:
In the examples port 80 and HTTP are used. However, you can open any accessible port and use any protocol definition for sending and retrieving responses. RSS feeds, XML output etc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top