tilde.club/html/public/fruitvote/GoPage.php
Lizzy Hunt 67e4b234d3
Some checks failed
continuous-integration/drone/push Build is failing
finish static page
2024-03-09 21:29:25 -07:00

89 lines
2.7 KiB
PHP

<?php
class GoPage {
private $page;
private $socket;
private $template;
public function __construct($page, $socket = "/home/lizzy/fruitvote/http.sock", $start_cmd="/home/simponic/fruitvote/start.sh", $template="../template.html") {
$this->page = $page;
$this->socket = $socket;
$this->template = $template;
// test if socket exists
if (!file_exists($socket)) {
// start the server
exec($start_cmd);
}
for ($i = 0; $i < 10; $i++) {
if (file_exists($socket)) {
break;
}
usleep(100_000); // wait 100ms
}
if (!file_exists($socket)) {
throw new Exception("Could not start server");
}
}
public function go() {
$ch = curl_init();
$url = "http://localhost".$this->page;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_UNIX_SOCKET_PATH, $this->socket);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// forward headers
$headers = array();
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) == "HTTP_") {
$key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
$headers[] = "$key: $value";
}
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// forward params depending on http method
if ($_SERVER['REQUEST_METHOD'] == "POST" || $_SERVER['REQUEST_METHOD'] == "PUT" || $_SERVER['REQUEST_METHOD'] == "DELETE") {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('php://input'));
} else {
$url .= "?".$_SERVER['QUERY_STRING'];
}
// forward cookies
$cookie = array();
foreach ($_COOKIE as $key => $value) {
$cookie[] = "$key=$value";
}
$output = curl_exec($ch);
curl_close($ch);
// forward headers back to client
$headers = explode("\n", $output);
foreach ($headers as $header) {
if (strpos($header, "HTTP/") === false) {
header($header);
}
}
// forward cookies back to client
$cookie = explode("\n", $output);
foreach ($cookie as $cookie) {
if (strpos($cookie, "Set-Cookie:") !== false) {
header($cookie);
}
}
return $output;
}
public function render() {
$response = $this->go();
$template = file_get_contents($this->template);
return str_replace("{{content}}", $response, $template);
}
}