Skip to content

Instantly share code, notes, and snippets.

@flashwave
Created September 12, 2017 23:44
Show Gist options
  • Save flashwave/b193e3cd8a571f616e31fae469ababb2 to your computer and use it in GitHub Desktop.
Save flashwave/b193e3cd8a571f616e31fae469ababb2 to your computer and use it in GitHub Desktop.
Attempt at making a Quote Of The Day server in PHP during an internet outage back in 2015
<?php
/*
* TCP only PHP Quote Of The Day Server
* Fuck the spec #GoogleChrome
* My Excuse for not being productive during this internet outage ^.^
* By Flashwave <http://flash.moe>
*/
// Configuration
$conf['address'] = '0.0.0.0';
$conf['port'] = 17;
$conf['quotesfile'] = 'quotes.txt';
// Enable reporting for all errors
error_reporting(-1);
// Allow the script to wait for connections
set_time_limit(0);
// Turn on implicit output flushing
ob_implicit_flush();
// Get quotes file
$quotes = file_get_contents($conf['quotesfile']);
// Make the quotes file a quotes array
$quotes = explode("\r\n", $quotes);
// Check if sockets extension is loaded
if(!extension_loaded('sockets'))
trigger_error('Sockets extension is not loaded.', E_USER_ERROR);
// TCP Bit
// Create a socket
if(($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === FALSE)
trigger_error('Failed to create TCP socket: '. socket_strerror(socket_last_error()), E_USER_ERROR);
// Bind the socket
if(socket_bind($sock, $conf['address'], $conf['port']) === FALSE)
trigger_error('Failed to bind TCP socket: '. socket_strerror(socket_last_error()), E_USER_ERROR);
// Start listening
if(socket_listen($sock) === FALSE)
trigger_error('Failed to listen on TCP socket: '. socket_strerror(socket_last_error()), E_USER_ERROR);
do {
if(($msgsock = socket_accept($sock)) === FALSE) {
trigger_error('Failed to accept things socket: '. socket_strerror(socket_last_error($sock)), E_USER_ERROR);
break;
}
// Block socket
socket_set_block($msgsock) . PHP_EOL;
$msg = $quotes[array_rand($quotes)];
socket_write($msgsock, $msg, strlen($msg));
// Close socket
socket_shutdown($msgsock, 2);
socket_close($msgsock);
} while(true);
// Close socket
socket_shutdown($sock, 2);
socket_close($sock);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment