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.

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.

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.

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

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

Leave a Reply