Skip to content

Instantly share code, notes, and snippets.

@luciferous
Created April 18, 2010 01:09
Show Gist options
  • Save luciferous/369941 to your computer and use it in GitHub Desktop.
Save luciferous/369941 to your computer and use it in GitHub Desktop.

PHP-WSGI

An example PHP-WSGI app:

<?php
require_once 'php-wsgi.php';
run_with_cgi(function($environ, $start_response) {
  try {
    $start_response('200 OK', array('Content-Type' => 'text/plain'));
    return array("Hello World\n");
  } catch (Exception $e) {
    $start_response(
      '500 Oops',
      array('Content-Type' => 'text/plain'),
      $e
    );
    return array('Return error body');
  }
});
<?php
class AssertionException extends Exception { }
function run_with_cgi($application) {
$environ = $_ENV;
$environ['wsgi.input'] = STDIN;
$environ['wsgi.errors'] = STDERR;
$environ['wsgi.version'] = array(1, 0);
$environ['wsgi.multithread'] = FALSE;
$environ['wsgi.multiprocess'] = TRUE;
$environ['wsgi.run_once'] = TRUE;
$environ['wsgi.url_scheme'] = (
in_array(getenv('HTTPS'), array('on', '1')) ? 'https' : 'http'
);
$headers_set = array();
$headers_sent = array();
$write = function($data) use (&$headers_set, &$headers_sent) {
if (!$data) return;
if (empty($headers_set)) {
throw new AssertionException('write() before start_response().');
}
else if (empty($headers_sent)) {
list($status, $response_headers) = ($headers_sent = $headers_set);
print "Status: $status\r\n";
foreach ($response_headers as $key => $value) {
printf("%s: %s\r\n", $key, $value);
}
print "\r\n";
}
print $data;
flush();
};
$start_response = function($status, $response_headers, $exc_info = NULL)
use ($write, &$headers_set, &$headers_sent) {
if ($exc_info && $headers_sent) {
throw $exc_info;
}
else if ($headers_set) {
throw new AssertionException("Headers already sent!");
}
$headers_set = array($status, $response_headers);
};
$result = $application($environ, $start_response);
$func = ($result instanceof Traversable) ? 'iterator_apply' : 'array_walk';
$func($result, $write);
if (empty($headers_sent)) {
$write('');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment