In PHP, stream_socket_sendto() sends data on a socket stream, optionally to a specific address.
Pass the payload string, optional flags, and an address when the transport needs one (common with UDP). It returns the number of bytes sent, or false on failure. Pair it with stream_socket_recvfrom() and stream_socket_pair() for offline demos.
Syntax
Call stream_socket_sendto() with the values you need. Start with this line.
PHP
$n = stream_socket_sendto($socket, $data);
Call
What it does
stream_socket_sendto($socket, 'ping')
Sends the text ping on a connected socket.
stream_socket_sendto($socket, $payload, 0, $addr)
Sends to an explicit address when required.
stream_socket_sendto($sock, "hi\n")
Sends a short line including a newline.
On a connected stream or pair end, you can often omit the address. For UDP-style sends, provide host:port in $address. Check the returned byte count against strlen($data).
Show the address argument shape with fixed tutorial text (listening server required for real UDP).
PHP
<?php
// Example: stream_socket_sendto($sock, 'hi', 0, '127.0.0.1:9999');
// Needs a real listening UDP server for a live send.
echo 'sample address: 127.0.0.1:9999', PHP_EOL;
echo 'sendto uses address for connectionless transports', PHP_EOL;
Output
sample address: 127.0.0.1:9999
sendto uses address for connectionless transports
How It Works
UDP-style sends need a destination address.
The string looks like host:port.
A listening server must exist for a real network send.
Use stream_socket_pair() when practicing offline.
Frequently Asked Questions
It sends a string on a socket stream and returns how many bytes were sent, or false on failure.
When the transport is connectionless (such as UDP) or otherwise requires an explicit destination.
Create a stream_socket_pair(), sendto on one end, and recvfrom on the other.
Only part of the data was sent. Send the remainder in another call if you need the full payload delivered.
fwrite() also writes to streams. sendto is the socket-oriented form with flags and an optional address.