PHPBuilder - Using Sockets in PHP



RSS Twitter
Articles Php Functions

Using Sockets in PHP

by: Armel Fauveau
|
May 10, 2001

Using sockets in PHP : Get articles from Usenet

PHP can open sockets on remote or local hosts. Here is a hands-on example of using such a socket: getting connected to a Usenet News Server, talking to this server, and downloading some articles for a precise newsgroup.

Opening a socket in PHP

Sockets are opened using fsockopen(). This function is both available in PHP3 and PHP4. It uses the following prototype :

<?php

int fsockopen 
    
(string hostname
        
int port [, 
        
int errno [, 
        
string errstr [, 
        
double timeout]]])
?>
For the Internet domain, it will open a TCP socket connection to hostname on port port. hostname may in this case be either a fully qualified domain name or an IP address. For UDP connections, you need to explicitly specify 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.
More information about fsockopen() : http://www.php.net/manual/function.fsockopen.php

Network News Transfer Protocol

Accessing a Usenet News Server requires using a specific protocol, called NNTP and standing for Network News Transfer Protocol.
This protocol is higly detailed in RFC977 (Request For Comment number 977), which is available at : http://www.w3.org/Protocols/rfc977/rfc977.html
This document described precisely how to connect to and then dialog with the NNTP server thanks to the various commands available for the task.

Connecting

Connecting to the NNTP server requires knowing its hostname (or IP address) and the port it is listening on. You should include a timeout so that an unsuccessful attempt at connecting does not "freeze" the application.

<?php

$cfgServer    
"your.news.host";
$cfgPort    119;
$cfgTimeOut    10;

// open a socket
if(!$cfgTimeOut)
    
// without timeout
    
$usenet_handle fsockopen($cfgServer$cfgPort);
else
    
// with timeout
    
$usenet_handle fsockopen($cfgServer$cfgPort, &$errno, &$errstr$cfgTimeOut);

if(!
$usenet_handle) {
    echo 
"Connexion failed\n";
    exit();
}    
else {
    echo 
"Connected\n";
    
$tmp fgets($usenet_handle1024);
}

?>

1
|
2
|
3
|
4
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Armel Fauveau

Comment:



Comment:

(Maximum characters: 1200). You have characters left.