PHP.GT

WebEngine usage

Why WebEngine avoids superglobals

In plain PHP, it is common to read cookies directly from $_COOKIE. That works, but it means any code in the project can read from - and write to - global request state at any time.

WebEngine protects superglobals by default so request data is accessed through explicit objects instead. This keeps page logic easier to test, because a function can receive the objects it needs rather than reaching into global state.

[!NOTE] WebEngine also uses PHP.GT/Input for query strings, form submissions, uploaded files, and request bodies. Cookie data is separate because browser cookies have their own request and response behaviour.

Using CookieHandler in application code

The useful pattern is to construct a CookieHandler near the edge of the application, then pass it to the code that needs cookies:

use GT\Cookie\CookieHandler;

function showIntro(CookieHandler $cookies):void {
	if($cookies->contains("dismissedIntro")) {
		return;
	}

	// Render the introductory message.
}

The same idea applies to actions that set cookies:

use GT\Cookie\CookieHandler;

function dismissIntro(CookieHandler $cookies):void {
	$cookies->set(
		"dismissedIntro",
		"1",
		new DateTime("+1 year"),
		secure: true,
		httponly: true,
	);
}

This keeps the dependency visible in the function signature. In a WebEngine project, that is the same style used by other PHP.GT components: page logic should depend on explicit objects rather than superglobals.

[!NOTE] The current WebEngine lifecycle also uses the incoming cookie array when initialising sessions, because PHP’s session system is identified by a browser cookie when cookie-based sessions are enabled.

Sessions and cookies

Cookies are often used to identify a session, but they should not usually contain the session data itself.

For example, a browser may store a session ID cookie. The server uses that ID to load the actual session data from server-side storage. That is different from storing a user’s private data directly in the cookie value.

When data belongs on the server, use PHP.GT/Session or another server-side store. When data is a small browser preference, CookieHandler can be enough on its own.

Security defaults in application code

When setting cookies from WebEngine page logic, prefer explicit security flags:

$cookies->set(
	"colourScheme",
	"dark",
	new DateTime("+6 months"),
	secure: true,
	httponly: true,
);

Use httponly: false only when JavaScript really does need to read the cookie. Use secure: true when the site is served over HTTPS, which should be the normal production setup.


Next, see the API reference for the complete public API of this package.