Skip to content

Examples

Greg Bowler edited this page Apr 24, 2026 · 2 revisions

This page collects a few small examples that show the shape of the library in practice.

Build a request from globals

use GT\Http\RequestFactory;

$request =new RequestFactory()
	->createServerRequestFromGlobalState(
		$_SERVER,
		$_FILES,
		$_GET,
		$_POST
	);

echo $request->getMethod();
echo $request->getUri()->getPath();

Create a text response

use GT\Http\Response;

$response = new Response();
$response = $response
	->withStatus(200)
	->withHeader("Content-Type", "text/plain; charset=UTF-8");

$response->getBody()->write("Everything is working.");

Redirect to another page

use GT\Http\Response;

$response = new Response();
$response->redirect("/login", 303);

Read and change URI parts

use GT\Http\Uri;

$uri = new Uri("https://example.com/search?q=phpgt&page=1");

$nextPage = $uri->withQueryValue("page", "2");
$withoutQuery = $uri->withQuery("");

Work with headers

use GT\Http\Header\ResponseHeaders;

$headers = new ResponseHeaders();
$headers->add("Cache-Control", "no-store");
$headers->add("Set-Cookie", "theme=light; Path=/");
$headers->add("Set-Cookie", "session=abc123; HttpOnly; Path=/");

print_r($headers->getAll("Set-Cookie"));

Use FormData

use GT\Http\FormData;

$formData = new FormData();
$formData->append("name", "Cody");
$formData->append("interest", "Mathematics");
$formData->append("interest", "Cryptography");

echo (string)$formData;

Use URLSearchParams

use GT\Http\URLSearchParams;

$params = new URLSearchParams();
$params->append("page", "2");
$params->append("filter", "new");
$params->append("filter", "popular");

echo (string)$params;

Wrap $_SERVER in ServerInfo

use GT\Http\ServerInfo;

$serverInfo = new ServerInfo($_SERVER);

echo $serverInfo->getRequestMethod();
echo $serverInfo->getFullUri();

Throw an HTTP status exception

use GT\Http\ResponseStatusException\ClientError\HttpNotFound;

if(!$record) {
	throw new HttpNotFound("The requested record does not exist.");
}

Choose a response class from Accept

use GT\Http\Response;
use GT\Http\ResponseFactory;

class HtmlResponse extends Response {}
class JsonResponse extends Response {}

ResponseFactory::registerResponseClass(HtmlResponse::class, "text/html");
ResponseFactory::registerResponseClass(JsonResponse::class, "application/json");

$response = ResponseFactory::create($request);

Clone this wiki locally