Do not pass an unchecked port to fsockopen() or stream_socket_client(). Parse it as an integer and require a value from 1 through 65535 before constructing the endpoint, so invalid values cannot connect to an unintended service.
Last updated: October 24, 2026.
<?php
function openTcpSocket(string $host, mixed $rawPort)
{
$port = filter_var(
$rawPort,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => 65535]]
);
if ($port === false) {
throw new InvalidArgumentException('Port must be between 1 and 65535.');
}
$socket = fsockopen(
"tcp://{$host}",
$port,
$errorCode,
$errorMessage,
5.0
);
if ($socket === false) {
throw new RuntimeException("Socket connection failed ({$errorCode}).");
}
return $socket;
}Keep the validated integer separate from the endpoint string. The five-second timeout limits the connection phase; set read and write timeouts separately when the application continues using the returned stream.
Validate before calling the socket function
The fsockopen() documentation accepts a host and port and returns a stream or false. Application code should not depend on a particular PHP version or operating system to reject an out-of-range value. Explicit validation produces predictable behavior and makes the accepted boundary visible during review.
Port zero has special meaning in some server-side APIs that ask the operating system to choose an available port, but it is not an appropriate destination for an ordinary client connection. The IANA service name and port registry describes the 16-bit port space and registered service assignments. A numerically valid port is not automatically an allowed destination; production applications should also restrict hosts and services to an approved list.
Keep connection policy outside raw input
If users select a service, map a known service name to a configured host and port instead of accepting an arbitrary network endpoint. This reduces server-side request forgery risk, accidental access to internal services, and mistakes caused by copied configuration. Resolve and log the final destination without recording credentials.
The PHP Internet transport documentation explains the tcp:// and udp:// transports. Use TLS when the protocol requires it, verify certificates, and never treat a successful TCP connection as proof that the expected application protocol is present. Close the stream with fclose() when finished. Continue with accepting non-blocking socket connections, detecting PHP socket timeouts, and using a Unix socket with PHP cURL.