search
HomeBackend DevelopmentPHP TutorialIn-depth explanation and example analysis of php socket_PHP tutorial

In this chapter you will learn about the fascinating and confusing Sockets. Sockets are an underutilized feature in PHP. Today you will see how to generate a server that can use the client connection, and use the socket on the client to connect, and the server will send detailed processing information to the client.
When you see the complete socket process, you will use it in future program development. The server is an HTTP server that allows you to connect, and the client is a web browser. This is a single client/server relationship.

◆ Socket Basics
PHP uses Berkley's socket library to create its connections. You can know that socket is just a data structure. You use this socket data structure to start a session between the client and the server. This server is always listening and preparing to generate a new session. When a client connects to the server, it opens a port on which the server is listening for a session. At this time, the server accepts the client's connection request and then performs a cycle. Now the client can send information to the server, and the server can send information to the client.
To generate a Socket, you need three variables: a protocol, a socket type and a public protocol type. There are three protocols to choose from when generating a socket. Continue reading below to get detailed protocol content.
Defining a public protocol type is an essential element for connection. In the table below we take a look at the common protocol types.

Table 1: Protocol
Name/Constant Description
AF_INET This is most of the protocols used to generate sockets, using TCP or UDP for transmission, and used in IPv4 addresses
AF_INET6 is similar to the above, but it is used for IPv6 addresses
AF_UNIX local protocol, used on Unix and Linux systems. It is rarely used. It is generally used when the client and server are on the same computer.

Table 2: Socket type
Name/constant description
SOCK_STREAM This protocol is a sequential, reliable, data-complete byte stream-based connection. This is the most commonly used socket type. This socket uses TCP for transmission.
SOCK_DGRAM This protocol is a connectionless, fixed-length transfer call. This protocol is unreliable and uses UDP for its connections.
SOCK_SEQPACKET This protocol is a dual-line, reliable connection that sends fixed-length data packets for transmission. This package must be accepted completely before it can be read.
SOCK_RAW This socket type provides single network access. This socket type uses the ICMP public protocol. (ping and traceroute use this protocol)
SOCK_RDM This type is rarely used and is not implemented on most operating systems. It is provided for the data link layer and does not guarantee the order of data packets

Table 3: Public Protocol
Name/Constant Description
ICMP Internet Control Message Protocol, mainly used on gateways and hosts to check network conditions and report error messages
UDP User Datagram Protocol, which is a connectionless, unreliable transmission protocol
TCP Transmission Control Protocol, which is the most commonly used reliable public protocol, can ensure that the data packet can reach the recipient. If an error occurs during transmission, it will resend the errored packet.

Now that you know the three elements to generate a socket, we use the socket_create() function in PHP to generate a socket. This socket_create() function requires three parameters: a protocol, a socket type, and a public protocol. The socket_create() function returns a resource type containing the socket if it succeeds, or false if it fails.
Resourece socket_create(int protocol, int socketType, int commonProtocol);

Now you create a socket, then what? PHP provides several functions for manipulating sockets. You can bind a socket to an IP, listen to a socket's communication, and accept a socket; now let's look at an example to understand how the function generates, accepts, and listens to a socket.

Copy code The code is as follows:

$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
socket_bind($socket, 'localhost', 1337);
socket_listen($socket);
// More socket functionality to come
?>

The above example generates your own server. The first line of the example,
$commonProtocol = getprotobyname("tcp");
Use the public protocol name to get a protocol type. The TCP public protocol is used here. If you want to use UDP or ICMP protocol, then you should change the parameters of the getprotobyname() function to "udp" or "icmp". Another alternative is to specify SOL_TCP or SOL_UDP in the socket_create() function instead of using the getprotobyname() function.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
The second line of the example generates a socket and returns an instance of the socket resource. After you have an instance of the socket resource, you must bind the socket to an IP address and a port.
socket_bind($socket, ‘localhost’, 1337);
Here you bind the socket to the local computer (127.0.0.1) and bind the socket to your 1337 port. Then you need to listen for all incoming socket connections.
socket_listen($socket);
After the fourth line, you need to understand all socket functions and their usage.

Table 4: Socket function
Function name description
socket_accept() accepts a Socket connection
socket_bind() binds the socket to an IP address and port
socket_clear_error() clears the socket error or the last error code
socket_close() closes a socket resource
socket_connect() starts a socket connection
socket_create_listen() opens a socket listening on the specified port
socket_create_pair() generates a pair of indistinguishable sockets into an array
socket_create() generates a socket, which is equivalent to generating a socket data structure
socket_get_option() gets the socket options
socket_getpeername() gets the remote Similar to the IP address of the host
socket_getsockname() Gets the IP address of the local socket
socket_iovec_add() Adds a new vector to a scatter/aggregate array
socket_iovec_alloc() This function creates a function that can send, receive, read and write The iovec data structure
socket_iovec_delete() deletes an allocated iovec
socket_iovec_fetch() returns the data of the specified iovec resource
socket_iovec_free() releases an iovec resource
socket_iovec_set() sets the iovec data new Value
socket_last_error() Get the last error code of the current socket
socket_listen() Listen to all connections by the specified socket
socket_read() Read the data of the specified length
socket_readv() Read from scatter/ Aggregate the data from the array
socket_recv() End the data from the socket to the cache
socket_recvfrom() Accept the data from the specified socket, if not specified, the current socket will be defaulted
socket_recvmsg() Accept the message from iovec
socket_select() Multiple selection
socket_send() This function sends data to the connected socket
socket_sendmsg() Sends a message to socket
socket_sendto() Sends a message to the socket of the specified address
socket_set_block () Set the socket to block mode
socket_set_nonblock() Set the socket to non-block mode
socket_set_option() Set the socket option
socket_shutdown() This function allows you to close reading, writing, or the specified socket
socket_strerror() returns the detailed error with the specified error number
socket_write() writes data to the socket cache
socket_writev() writes data to the scatter/aggregate array

(Note: The function introduction has deleted part of the original text. It is recommended to refer to the original English text for detailed use of functions, or refer to the PHP manual)
All the above functions are about sockets in PHP. Use For these functions, you must open your socket. If you have not opened it, please edit your php.ini file and remove the comment in front of the following line:
extension=php_sockets.dll
If you cannot remove the comment, then please use the following code to load the extension library:

Copy the code The code is as follows:

if(!extension_loaded('sockets'))
{
if(strtoupper(substr(PHP_OS, 3)) == “WIN”)
{
dl('php_sockets.dll');
}
else
{
dl('sockets.so');
}
}
?>

If you don't know whether your socket is open, then you can use the phpinfo() function to determine whether the socket is open. You can check whether the socket is open by checking the phpinfo information. As shown below:
View phpinfo()’s information about socket

◆ Generate a server
Now let’s improve the first example. You need to listen to a specific socket and handle user connections.

Copy code The code is as follows:

$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
socket_bind($socket, 'localhost' , 1337);
socket_listen($socket);
// Accept any incoming connections to the server
$connection = socket_accept($socket);
if($connection)
{
socket_write($connection, "You have connected to the socket...nr");
}
?>

You should use your command prompt to run This example. The reason is because a server will be generated here, not a Web page. If you try to run this script using a web browser, there's a good chance it will exceed the 30-second limit. You can use the code below to set an infinite run time, but it is recommended to use the command prompt to run.
set_time_limit(0);
A simple test of this script in your command prompt:
Php.exe example01_server .php
If you do not set the path of the php interpreter in the system environment variable, then you will need to specify the detailed path to php.exe. When you run the server, you can test the server by connecting to port 1337 via telnet. As shown below:

There are three problems with the server side above:
1. It cannot accept multiple connections.
2. It only completes one command.
3. You cannot connect to this server through a web browser.
This first problem is easier
to solve, you can use an application to connect to the server every time. But the next problem is that you need to use a Web page to connect to the server, which is more difficult. You can have your server accept the connection, write some data to the client (if it must write it), close the connection and wait for the next connection.
Improve the previous code and generate the following code to make your new server:

Copy the code The code is as follows:

// Set up our socket
$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
socket_bind($socket, 'localhost', 1337);
socket_listen($socket);
// Initialize the buffer
$buffer = "NO DATA";
while(true)
{
// Accept any connections coming in on this socket

$connection = socket_accept($socket);
printf("Socket connectedrn");
// Check to see if there is anything in the buffer
if($buffer != "")
{
printf("Something is in the buffer...sending data...rn");
socket_write($connection, $buffer . "rn");
printf("Wrote to socketrn");
}
else
{
printf("No Data in the bufferrn");
}
// Get the input
while($data = socket_read($connection, 1024, PHP_NORMAL_READ))
{
$buffer = $data;
socket_write($connection, "Information Receivedrn");
printf("Buffer: " . $buffer . "rn");
}
socket_close($connection);
printf("Closed the socketrnrn");
}
?>


What should this server do? It initializes a socket and opens a cache to send and receive data. It waits for a connection and once a connection is made it prints "Socket connected" on the screen on the server side. This server checks the buffer and if there is data in the buffer, it sends the data to the connected computer. It then sends an accept message for this data. Once it accepts the message, it saves the message to the data, makes the connected computer aware of the message, and finally closes the connection. When the connection is closed, the server starts processing the next connection. (Bad translation, original text attached)
This is what the server does. It initializes the socket and the buffer that you use to receive
and send data. Then it waits for a connection. Once a connection is created it prints “Socket connected” to the screen the server is running on. The server then checks to see if
there is anything in the buffer; if there is, it sends the data to the connected computer.
After it sends the data it waits to receive information. Once it receives information it stores
it in the data, lets the connected computer know that it has received the information, and
then closes the connection. After the connection is closed, the server starts the whole
process again.

◆ Generating a client
Handling the second problem is easy. You need to generate a php page, connect to a socket, send some data to its cache and process it. Then after you process the data again, you can send your data to the server. On another client connection, it will process that data.
To solve the second problem is very easy. You need to create a PHP page that connects to
a socket, receive any data that is in the buffer, and process it. After you have processed the
data in the buffer you can send your data to the server. When another client connects, it
will process the data you sent and the client will send more data back to the server.

The following example demonstrates the use of socket:

Copy the code The code is as follows:

// Create the socket and connect
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$connection = socket_connect($socket,'localhost', 1337);
while($buffer = socket_read( $socket, 1024, PHP_NORMAL_READ))
{
if($buffer == “NO DATA”)
{
echo(“

NO DATA

”);
break;
}
else
{
// Do something with the data in the buffer
echo(“

Buffer Data: “ . $buffer . “”);
}
}
echo(“

Writing to Socket

”);
// Write some test data to our socket
if (!socket_write($socket, “SOME DATArn”))
{
echo(“

Write failed

”);
}
// Read any response from the socket
while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ))
{
echo(“

Data sent was: SOME DATA
Response was:” . $buffer . "

");
}
echo("

Done Reading from Socket

");
?>

This The example code demonstrates the client connecting to the server. The client reads the data. If this is the first connection to arrive in this cycle, the server will send "NO DATA" back to the client. If this happens, the client is on top of the connection. The client sends its data to the server, the data is sent to the server, and the client waits for a response. Once the response is received, it writes the response to the screen.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327568.htmlTechArticleIn this chapter you will learn about the fascinating and confusing Sockets. Sockets are an underutilized feature in PHP. Today you will see the creation of a client that can use...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools