Using PHP To Send A UDP Message

Previously I’ve written about sending UDP datagrams using Perl and JavaScript with node.js.

As I’ve been using a lot of PHP recently, I thought I’d show how to send data over UDP using PHP.

If you’ve not come across UDP before, it’s a simple protocol for sending messages over the internet that aren’t guaranteed to arrive. You just fire them off and hope they arrive.

The previous examples showed sending a simple heartbeat message, a string simply saying “PyHB”, to a server listening on port 43278. I’ll do the same in this example.

Firstly we’ll setup a few variables saying where we’ll be sending the the message to, along with how often we want to send the message and what it should say.

$server_ip = '127.0.0.1';
$server_port = 43278;
$beat_period = 5;
$message = 'PyHB';

Now we have to create the socket, using the socket_create function. We need the domain to be of type AF_INET as we are using an IP4 address for our server, the type needs to be SOCK_DGRAM and the protocol needs to be SOL_UDPas we’re sending a UDP datagram.

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP))

It’s time to send the message now, and to do this we can use PHP’s socket_sendto function. This function takes the parameters of the socket to send the message over, the message itself, the length of the message, some flags, the destination address of the message and the port to send it to. We’re not setting any flags so we can just set this field to 0. The following code will do the trick.

socket_sendto($socket, $message, strlen($message), 0, $server_ip, $server_port);

Let’s wrap this up in a loop that sends the message every $beat_period seconds.

<php
$server_ip   = '127.0.0.1';
$server_port = 43278;
$beat_period = 5;
$message     = 'PyHB';
print "Sending heartbeat to IP $server_ip, port $server_portn";
print "press Ctrl-C to stopn";
if ($socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) {
  while (1) {
    socket_sendto($socket, $message, strlen($message), 0, $server_ip, $server_port);
    print "Time: " . date("%r") . "n";
    sleep($beat_period);
  }
} else {
  print("can't create socketn");
}
?>

This code is run on the command line, and not via a web server.

3 thoughts on “Using PHP To Send A UDP Message”

  1. Hi, love your article, I wonder if it is possible to wrap your code around a HTML image button so this button will broadcast a UDP text message (when clicekd) to a local UDP server listening to a certain port. Additionally, the UDP server is a custom program and does not use any of the web technology such as php perl etc so all code has to be done on client side (the HTML page). Can you give me some advice please? thanks.

    1. PHP runs server side, so you won’t be able to use this code to run in the client. For that, you’d need to look at JavaScript.

Comments are closed.