Created
September 29, 2023 20:54
-
-
Save missoxd/cdc0c818c764bad927c23f9c386c9557 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Define the default socket timeout | |
ini_set('default_socket_timeout', 360); | |
// Start Socket Server | |
$errno = 0; | |
$errstr = ''; | |
$socket = stream_socket_server('tcp://0.0.0.0:8000', $errno, $errstr); | |
if (!$socket) { | |
die($errstr .'('. $errno .')'); | |
} | |
// Listen to connections | |
echo 'Stream Socket Server Initialized!' . PHP_EOL; | |
while ($conn = stream_socket_accept($socket)) { | |
// Read HTTP request | |
$request = fread($conn, 2048); | |
$requestPath = explode("\r\n", $request); | |
$requestPath = trim(preg_replace('#GET|HTTP/1.1#', '', $requestPath[0]), ' /'); | |
// Build HTTP response | |
$body = '<h1>Welcome to '. $requestPath .'!</h1><p>Welcome to my custom HTTP PHP socket server.</p>'; | |
$httpResponse = implode("\r\n", [ | |
'HTTP/1.1 200 OK', | |
'Date: '. date('D, m M Y H:i:s \G\M\T'), | |
'Server: My Custom PHP Server', | |
'Connection: close', | |
'Content-Type: text/html', | |
'Content-Length: '. strlen($body), | |
'', | |
$body | |
]); | |
// Log HTTP response to console | |
echo PHP_EOL . PHP_EOL . ' - - - - - ' . PHP_EOL; | |
echo $httpResponse; | |
// Send HTTP response to client | |
fwrite($conn, $httpResponse); | |
// Close the income connection | |
fclose($conn); | |
} | |
fclose($socket); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment