1. Go to this page and download the library: Download anonymhk/http library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
anonymhk / http example snippets
nt = new React\Http\Browser();
$client->get('http://www.google.com/')->then(function (Psr\Http\Message\ResponseInterface $response) {
var_dump($response->getHeaders(), (string)$response->getBody());
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
= new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
return React\Http\Message\Response::plaintext(
"Hello World!\n"
);
});
$socket = new React\Socket\SocketServer('127.0.0.1:8080');
$http->listen($socket);
$browser->get($url, $headers)->then(function (Psr\Http\Message\ResponseInterface $response) {
// the final response will end up here
var_dump($response->getHeaders());
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
$browser = $browser->withFollowRedirects(false);
$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
// any redirects will now end up here
var_dump($response->getHeaders());
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
use function React\Async\await;
$browser = new React\Http\Browser();
$promise = $browser->get('http://example.com/');
try {
$response = await($promise);
// response successfully received
} catch (Exception $e) {
// an error occurred while performing the request
}
use function React\Async\await;
use function React\Promise\all;
$promises = array(
$browser->get('http://example.com/'),
$browser->get('http://www.example.org/'),
);
$responses = await(all($promises));
// watch out if array contains many elements
foreach ($urls as $url) {
$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
var_dump($response->getHeaders());
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
}
// wraps Browser in a Queue object that executes no more than 10 operations at once
$q = new Clue\React\Mq\Queue(10, null, function ($url) use ($browser) {
return $browser->get($url);
});
foreach ($urls as $url) {
$q($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
var_dump($response->getHeaders());
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
}
$http = new React\Http\HttpServer($handler);
$socket = new React\Socket\SocketServer('0.0.0.0:8080');
$http->listen($socket);
$http = new React\Http\HttpServer(
new React\Http\Middleware\StreamingRequestMiddleware(),
new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers
new React\Http\Middleware\RequestBodyBufferMiddleware(2 * 1024 * 1024), // 2 MiB per request
new React\Http\Middleware\RequestBodyParserMiddleware(),
$handler
);
$http = new React\Http\HttpServer(
new React\Http\Middleware\StreamingRequestMiddleware(),
$handler
);
$http = new React\Http\HttpServer($handler);
$socket = new React\Socket\SocketServer('0.0.0.0:8080');
$http->listen($socket);
$http = new React\Http\HttpServer($handler);
$socket = new React\Socket\SocketServer('tls://0.0.0.0:8443', array(
'tls' => array(
'local_cert' => __DIR__ . '/localhost.pem'
)
));
$http->listen($socket);
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
$body = "The method of the request is: " . $request->getMethod() . "\n";
$body .= "The requested path is: " . $request->getUri()->getPath() . "\n";
return React\Http\Message\Response::plaintext(
$body
);
});
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
$body = "Your IP is: " . $request->getServerParams()['REMOTE_ADDR'] . "\n";
return React\Http\Message\Response::plaintext(
$body
);
});
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
$queryParams = $request->getQueryParams();
$body = 'The query parameter "foo" is not set. Click the following link ';
$body .= '<a href="/?foo=bar">to use query parameter in your request</a>';
if (isset($queryParams['foo'])) {
$body = 'The value of "foo" is: ' . htmlspecialchars($queryParams['foo']);
}
return React\Http\Message\Response::html(
$body
);
});
$http = new React\Http\HttpServer(
new React\Http\Middleware\StreamingRequestMiddleware(),
function (Psr\Http\Message\ServerRequestInterface $request) {
$body = $request->getBody();
assert($body instanceof Psr\Http\Message\StreamInterface);
assert($body instanceof React\Stream\ReadableStreamInterface);
return new React\Promise\Promise(function ($resolve, $reject) use ($body) {
$bytes = 0;
$body->on('data', function ($data) use (&$bytes) {
$bytes += strlen($data);
});
$body->on('end', function () use ($resolve, &$bytes){
$resolve(React\Http\Message\Response::plaintext(
"Received $bytes bytes\n"
));
});
// an error occures e.g. on invalid chunked encoded data or an unexpected 'end' event
$body->on('error', function (Exception $e) use ($resolve, &$bytes) {
$resolve(React\Http\Message\Response::plaintext(
"Encountered error after $bytes bytes: {$e->getMessage()}\n"
)->withStatus(React\Http\Message\Response::STATUS_BAD_REQUEST));
});
});
}
);
$http = new React\Http\HttpServer(
new React\Http\Middleware\StreamingRequestMiddleware(),
function (Psr\Http\Message\ServerRequestInterface $request) {
$size = $request->getBody()->getSize();
if ($size === null) {
$body = "The request does not contain an explicit length. ";
$body .= "This example does not accept chunked transfer encoding.\n";
return React\Http\Message\Response::plaintext(
$body
)->withStatus(React\Http\Message\Response::STATUS_LENGTH_REQUIRED);
}
return React\Http\Message\Response::plaintext(
"Request body size: " . $size . " bytes\n"
);
}
);
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
$key = 'greeting';
if (isset($request->getCookieParams()[$key])) {
$body = "Your cookie value is: " . $request->getCookieParams()[$key] . "\n";
return React\Http\Message\Response::plaintext(
$body
);
}
return React\Http\Message\Response::plaintext(
"Your cookie has been set.\n"
)->withHeader('Set-Cookie', $key . '=' . urlencode('Hello world!'));
});
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
$stream = new ThroughStream();
// send some data every once in a while with periodic timer
$timer = Loop::addPeriodicTimer(0.5, function () use ($stream) {
$stream->write(microtime(true) . PHP_EOL);
});
// end stream after a few seconds
$timeout = Loop::addTimer(5.0, function() use ($stream, $timer) {
Loop::cancelTimer($timer);
$stream->end();
});
// stop timer if stream is closed (such as when connection is closed)
$stream->on('close', function () use ($timer, $timeout) {
Loop::cancelTimer($timer);
Loop::cancelTimer($timeout);
});
return new React\Http\Message\Response(
React\Http\Message\Response::STATUS_OK,
array(
'Content-Type' => 'text/plain'
),
$stream
);
});
$http = new React\Http\HttpServer(function (ServerRequestInterface $request) {
return new React\Http\Message\Response(
React\Http\Message\Response::STATUS_OK,
array(
'Server' => 'PHP/3'
)
);
});
$http = new React\Http\HttpServer(function (ServerRequestInterface $request) {
return new React\Http\Message\Response(
React\Http\Message\Response::STATUS_OK,
array(
'Server' => ''
)
);
});
$http = new React\Http\HttpServer(function (ServerRequestInterface $request) {
return new React\Http\Message\Response(
React\Http\Message\Response::STATUS_OK,
array(
'Date' => gmdate('D, d M Y H:i:s \G\M\T')
)
);
});
$http = new React\Http\HttpServer(function (ServerRequestInterface $request) {
return new React\Http\Message\Response(
React\Http\Message\Response::STATUS_OK,
array(
'Date' => ''
)
);
});
$http = new React\Http\HttpServer(
function (Psr\Http\Message\ServerRequestInterface $request, callable $next) {
$request = $request->withHeader('Request-Time', time());
return $next($request);
},
function (Psr\Http\Message\ServerRequestInterface $request) {
return new React\Http\Message\Response(React\Http\Message\Response::STATUS_OK);
}
);
$http = new React\Http\HttpServer(
function (Psr\Http\Message\ServerRequestInterface $request, callable $next) {
$promise = React\Promise\resolve($next($request));
return $promise->then(function (ResponseInterface $response) {
return $response->withHeader('Content-Type', 'text/html');
});
},
function (Psr\Http\Message\ServerRequestInterface $request) {
return new React\Http\Message\Response(React\Http\Message\Response::STATUS_OK);
}
);
$http = new React\Http\HttpServer(
function (Psr\Http\Message\ServerRequestInterface $request, callable $next) {
$promise = new React\Promise\Promise(function ($resolve) use ($next, $request) {
$resolve($next($request));
});
return $promise->then(null, function (Exception $e) {
return React\Http\Message\Response::plaintext(
'Internal error: ' . $e->getMessage() . "\n"
)->withStatus(React\Http\Message\Response::STATUS_INTERNAL_SERVER_ERROR);
});
},
function (Psr\Http\Message\ServerRequestInterface $request) {
if (mt_rand(0, 1) === 1) {
throw new RuntimeException('Database error');
}
return new React\Http\Message\Response(React\Http\Message\Response::STATUS_OK);
}
);
$browser = new React\Http\Browser();
// constructor signature as of v1.5.0
$browser = new React\Http\Browser(?ConnectorInterface $connector = null, ?LoopInterface $loop = null);
// legacy constructor signature before v1.5.0
$browser = new React\Http\Browser(?LoopInterface $loop = null, ?ConnectorInterface $connector = null);
$body = new React\Stream\ThroughStream();
Loop::addTimer(1.0, function () use ($body) {
$body->end("hello world");
});
$browser->requestStreaming('POST', $url, array('Content-Length' => '11'), $body);
$browser = $browser->withTimeout(10.0);
$browser = $browser->withTimeout(false);
$browser = $browser->withTimeout(true);
$browser = $browser->withFollowRedirects(5);
$browser = $browser->withFollowRedirects(0);
$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
// only non-redirected responses will now end up here
var_dump($response->getHeaders());
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
$browser = $browser->withFollowRedirects(false);
$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
// any redirects will now end up here
var_dump($response->getHeaderLine('Location'));
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
$browser = $browser->withFollowRedirects(true);
$browser = $browser->withRejectErrorResponse(false);
$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
// any HTTP response will now end up here
var_dump($response->getStatusCode(), $response->getReasonPhrase());
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
$browser = $browser->withRejectErrorResponse(true);
$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
// any successful HTTP response will now end up here
var_dump($response->getStatusCode(), $response->getReasonPhrase());
}, function (Exception $e) {
if ($e instanceof React\Http\Message\ResponseException) {
// any HTTP response error message will now end up here
$response = $e->getResponse();
var_dump($response->getStatusCode(), $response->getReasonPhrase());
} else {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
}
});
$browser = $browser->withBase('http://api.example.com/v3/');
// will request http://api.example.com/v3/users
$browser->get('users')->then(…);
$response = React\Http\Message\Response::html(
"<h1>Error</h1>\n<p>Invalid user name given.</p>\n"
)->withStatus(React\Http\Message\Response::STATUS_BAD_REQUEST);
$response = React\Http\Message\Response::plaintext(
"Error: Invalid user name given.\n"
)->withStatus(React\Http\Message\Response::STATUS_BAD_REQUEST);
$response = React\Http\Message\Response::xml(
"<error><message>Invalid user name given.</message></error>\n"
)->withStatus(React\Http\Message\Response::STATUS_BAD_REQUEST);
$http = new React\Http\HttpServer(
new React\Http\Middleware\StreamingRequestMiddleware(),
function (Psr\Http\Message\ServerRequestInterface $request) {
$body = $request->getBody();
assert($body instanceof Psr\Http\Message\StreamInterface);
assert($body instanceof React\Stream\ReadableStreamInterface);
return new React\Promise\Promise(function ($resolve) use ($body) {
$bytes = 0;
$body->on('data', function ($chunk) use (&$bytes) {
$bytes += \count($chunk);
});
$body->on('close', function () use (&$bytes, $resolve) {
$resolve(new React\Http\Message\Response(
React\Http\Message\Response::STATUS_OK,
[],
"Received $bytes bytes\n"
));
});
});
}
);
$http = new React\Http\HttpServer(
new React\Http\Middleware\StreamingRequestMiddleware(),
new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers
new React\Http\Middleware\RequestBodyBufferMiddleware(2 * 1024 * 1024), // 2 MiB per request
new React\Http\Middleware\RequestBodyParserMiddleware(),
$handler
);
$http = new React\Http\HttpServer(
new React\Http\Middleware\LimitConcurrentRequestsMiddleware(10),
$handler
);
$http = new React\Http\HttpServer(
new React\Http\Middleware\StreamingRequestMiddleware(),
new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers
new React\Http\Middleware\RequestBodyBufferMiddleware(2 * 1024 * 1024), // 2 MiB per request
new React\Http\Middleware\RequestBodyParserMiddleware(),
$handler
);
$http = new React\Http\HttpServer(
new React\Http\Middleware\StreamingRequestMiddleware(),
new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers
new React\Http\Middleware\RequestBodyBufferMiddleware(2 * 1024 * 1024), // 2 MiB per request
new React\Http\Middleware\RequestBodyParserMiddleware(),
new React\Http\Middleware\LimitConcurrentRequestsMiddleware(1), // only execute 1 handler (no concurrency)
$handler
);