LorenzoD
LorenzoD

Reputation: 15

PHP script connecting TCP/IP server?

I know that PHP does allow you to create a server but what about client? I would need a script that connects to my TCP/IP server on given port and send some data. Is that possible in PHP and if so, could you help me please? I did not find anything useful. I have my TCP/IP server running on port 1301 and I would need users to be able by clicking on web page send one char to the server.

Upvotes: 0

Views: 2965

Answers (4)

Sleavely
Sleavely

Reputation: 1683

I've used this piece before. It's fairly simple; it connects to $ip_address on port $port, and sends the $sendData data to the server, and then reads the response and returns the response.

$sendData = chr(6).chr(0).chr(255).chr(255).'info';
function sendAndGetResponse($ip_address, $port, $sendData){
$socketHandler=@fsockopen($ip_address, $port, $errno, $errstr, 1);
if(!$socketHandler)
{
    return false; //offline
}
else
{
    $response = '';
    stream_set_timeout($socketHandler, 2);
    fwrite($socketHandler, $sendData);
    while (!feof($socketHandler))
    {
        stream_set_timeout($socketHandler, 2);
        $response .= fgets($socketHandler, 1024);
    }
    fclose($socketHandler);
    return $response;
}
}

Upvotes: 2

Sethunath K M
Sethunath K M

Reputation: 4761

You can use CURL if it is HTTP server or create a socket connection http://php.net/manual/en/function.socket-connect.php

Upvotes: 1

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

It's similar to how you would create a server. I'd recommend taking a look at the documentation for socket_connect.

Summaries:

Workflow:

  • Create the socket
  • Optionally bind it
  • Connect to the server
  • Read/write data
  • Close the socket

Upvotes: 2

Artjom Kurapov
Artjom Kurapov

Reputation: 6155

Yes, php can act as a HTTP-client with CURL, fsockopen and most easiest way to fetch URL - with file_get_contents()

Upvotes: -3

Related Questions