Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP Socket context options
Access to filesystem and various other stream wrappers can be customized by context options and parameters configured by stream_context_create() and stream_context_set_option() functions.
Following list shows various socket context options available for all wrappers that work over sockets, like tcp, http and ftp ?
Socket Context Options
| Option | Description |
|---|---|
| bindto | Specifies the IP address (either IPv4 or IPv6) and/or the port number used to access the network. (ip:port for IPv4 [ip]:port for IPv6). |
| backlog | Limits number of outstanding connections in socket's listen queue. |
| ipv6_v6only | Overrides the OS default regarding mapping IPv4 into IPv6. |
| so_reuseport | Allows multiple bindings to a same ip:port pair. |
| so_broadcast | Enables sending and receiving data to/from broadcast addresses. |
| tcp_nodelay | If TRUE, sets SOL_TCP,NO_DELAY=1 appropriately, disabling TCP Nagle algorithm. |
Example
Here's how to bind to a specific IP address when making HTTP requests ?
<?php
// Connect to the internet using the '192.168.0.100' IP
$opts = array(
'socket' => array(
'bindto' => '192.168.0.100:0',
),
);
$context = stream_context_create($opts);
// Use the context to fetch data
echo file_get_contents('http://www.example.com', false, $context);
?>
Multiple Socket Options Example
You can combine multiple socket options for more advanced configurations ?
<?php
$opts = array(
'socket' => array(
'bindto' => '0:80',
'backlog' => 128,
'so_reuseport' => true,
'tcp_nodelay' => true,
),
);
$context = stream_context_create($opts);
$server = stream_socket_server('tcp://localhost:8080', $errno, $errstr,
STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);
?>
Conclusion
Socket context options provide fine-grained control over network connections in PHP. Use them to specify binding addresses, configure connection limits, and optimize TCP behavior for your specific use cases.
Advertisements
