Stagepass

PHP on Stagepass

Optional plain PHP 8.2 for a small server endpoint next to a Webflow or Stagepass front end. No framework, no Composer, and no mail. Published CLI 2.4.0 writes it with stagepass new --php. Since 2.4.1 that scaffold also ships a web-root .htaccess.

loader 2.5.2cli 2.7.0PHP 8.2

What this is

The starter is one public file, api/action.php. Every request names an action. That name is looked up in an allowlist (api/actions.php) and then handed to a file in api/actions/. User input is never used as a file path or a function name. There is no mail in this starter, by design.

When to use it

Use it when a page needs a small endpoint: a form, a signup, or a webhook-style POST. Local requests go to https://your-project.sp/api/action.php, and the same path works on the host you upload to.

Skip it for heavy apps, queues, or anything that needs a framework.

How a request is routed

The browser or fetch calls /api/action.php with an action name in the query string or in a JSON body. action.php loads config, applies CORS, checks the origin, applies the rate limit, and checks the honeypot. The name must be in api/actions.php. The matching file in api/actions/ returns a callable and a JSON payload.

What you edit

Edit api/actions.php, the files in api/actions/, the project-root .env, and, if you need overrides, .php/config.php. Leave api/action.php and api/lib/ alone. Short comments in those files mark the same split.

Configuration

Copy api/.env.example to .env in the project root, the folder that contains api/. load_config() also reads .php/.env. A key that is already set in the real environment is left as it is. Set ALLOWED_ORIGINS to exact origins, scheme included, with no trailing slash: the .sp domain, the Webflow preview, and the public site. APP_ENV=local turns on a hidden boom action used only to test errors. Leave APP_ENV=production on a public host.

The same file holds the honeypot field name, the rate limit, the body size cap, and the timezone. Optional .php/config.php overrides .env. Keep .env out of git. Caddy already returns 404 for any path segment that starts with ., including /.env, /.php/, and /api/.env. Since 2.4.1 the PHP scaffold ships a web-root .htaccess, and stagepass build copies it to dist/.htaccess when "php": true and the project has one. It still does not copy .env, .php/.env, or .php/rate-limit/. A dist/.htaccess already on disk stays when the project has none. Published CLI 2.4.0 does not ship the file. stagepass build on 2.4.0 keeps a .htaccess you add yourself. nginx does not read .htaccess. The snippet is under Local development and hosting.

The document root is the folder that contains api/. After a normal deploy of dist/, that folder is the web root, and .php/config.php is in it. On Apache and nginx, .php/ is public unless hidden paths are denied. Since 2.4.1 the starter comments name that document root. load_config() reads the project-root .env and .php/.env. Published CLI 2.4.0 still says the config sits "outside the public root" and "outside the public api/ directory". Those sentences describe the layout relative to api/, not a second directory outside the web root. stagepass upgrade does not replace PHP sources, so a project created with 2.4.0 keeps that wording.

Adding an action

Create api/actions/your-name.php. The file must return a callable. Read fields with input_string() and validate with the shared helpers. Register the name, file, methods, honeypot, rate limit, and origin rule in api/actions.php. Call it from JavaScript with action: 'your-name'. Do not add a second public PHP file unless you have a strong reason.

A newsletter-style POST is the worked shape: require an email, throw ValidationException when it is invalid, return a small array on success, and register the name as POST with the honeypot and the origin check on.

Validation and errors

ValidationException becomes status: "fail" with HTTP 422 and per-field messages in data. Any other uncaught exception becomes status: "error" with HTTP 500. The 500 body is generic. The real message is only logged on the server.

Other fail cases: unknown action (404), wrong method (405), disallowed origin (403), too many requests (429).

Response shape

Every response is JSON with status, data, and message, plus a matching HTTP status code. That shape is JSend-like:

  • success (200): the handler return value is in data.
  • fail: the request was rejected. Details are in data.
  • error: an unexpected server failure, with no internal details.

In the browser, branch on result.status.

Calling it from JavaScript

sp.resolveLocalUrl (loader 2.5.0) returns a local HTTPS URL only during an active .sp session. Otherwise it returns an empty string. On a Webflow page, window.location.origin is the Webflow host. Webflow does not run PHP, so a fetch to that origin does not reach this API. origin and production in stagepass.json are Webflow hosts. There is no helper that turns them into the PHP base URL. The production fallback is the absolute URL of the PHP host, for example https://php.example.com/api/action.php. A relative /api/action.php only works when the page is already served from that host.

POST JSON with Content-Type: application/json and an empty honeypot field, hidden in CSS. The browser sends Origin. That value must be on ALLOWED_ORIGINS.

JavaScript
const path = '/api/action.php';
const phpHost = 'https://php.example.com';
const local = sp.vars.isLocal && sp.resolveLocalUrl(path);
const url = local || phpHost + path;
const result = await fetch(url, {
  method: 'POST',
  headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
  body: JSON.stringify({
    action: 'contact',
    name: 'Ada Lovelace',
    email: 'ada@example.com',
    message: 'Hello',
    website: '',
  }),
}).then((response) => response.json());

A simple GET check uses the same host: https://php.example.com/api/action.php?action=ping, or sp.resolveLocalUrl('/api/action.php') while a .sp session is active.

Published @stagepass/loader 2.5.0 global.d.ts augments Window with sp and stagepass (both StagepassAPI, including resolveLocalUrl, vars, and log) and declares global var sp / var stagepass. stagepass new and upgrade write compilerOptions.types including @stagepass/loader. The scaffold main.ts still uses a narrow cast for sp.log. The official types are wider.

Native Webflow forms

Keep the form in Webflow. Its success and error blocks stay as designed. In Webflow, give each field the name your action reads (name, email, message for contact) and add the custom attribute data-sp-action with the action name (for example contact) on the form element. Add the script below to the site (a tagged data-stagepass script in a Stagepass project, or in the head). It sends the fields as a form POST to api/action.php.

Why capture: Webflow's form script listens for submit on document after the event bubbles up and ignores preventDefault(). A submit listener on the form that only calls preventDefault() still sends the entry to Webflow as well. This listener runs in the capture phase and stops the event, so Webflow never sees it.

JavaScript
/**
 * Opt-in Stagepass submit for native Webflow forms (div.w-form).
 * Mark a form with data-sp-action="<action>". Reuses .w-form-done / .w-form-fail.
 */
(function () {
  const PHP_URL = 'https://php.example.com/api/action.php';

  document.addEventListener('submit', (event) => {
    const form = event.target;
    if (!(form instanceof HTMLFormElement) || !form.closest('.w-form')) return;
    const actionName = form.getAttribute('data-sp-action');
    if (!actionName) return;

    // Capture + stopImmediatePropagation: Webflow's jQuery handler is
    // delegated on document (bubble) and does not check defaultPrevented.
    event.preventDefault();
    event.stopImmediatePropagation();
    if (form.dataset.spBusy === '1') return;
    form.dataset.spBusy = '1';

    const wrap = form.closest('.w-form');
    const done = wrap.querySelector('.w-form-done');
    const fail = wrap.querySelector('.w-form-fail');
    const failChild = fail?.firstElementChild;
    if (failChild && failChild.dataset.spOrig == null) failChild.dataset.spOrig = failChild.textContent || '';
    const orig = failChild?.dataset.spOrig || 'Oops! Something went wrong while submitting the form.';
    form.querySelectorAll('[aria-invalid]').forEach((el) => el.removeAttribute('aria-invalid'));

    const btn = form.querySelector('input[type="submit"], button[type="submit"]');
    const label = btn ? (btn.value || btn.textContent) : '';
    const wait = btn?.getAttribute('data-wait');
    if (btn) {
      btn.disabled = true;
      if (wait) { if (btn.tagName === 'INPUT') btn.value = wait; else btn.textContent = wait; }
    }
    const restore = () => { delete form.dataset.spBusy; if (btn) { btn.disabled = false; if (btn.tagName === 'INPUT') btn.value = label; else btn.textContent = label; } };
    const showFail = (text) => {
      if (failChild) failChild.textContent = text;
      if (fail) { fail.style.display = 'block'; fail.focus(); }
      if (done) done.style.display = 'none'; form.style.display = '';
    };

    const body = new FormData(form);
    body.append('action', actionName);
    const url = (window.sp?.vars?.isLocal && sp.resolveLocalUrl?.('/api/action.php')) || PHP_URL;

    fetch(url, { method: 'POST', headers: { Accept: 'application/json' }, body })
      .then(async (res) => {
        let json = null;
        try { json = JSON.parse(await res.text()); } catch (_) {}
        restore();
        if (!json) return showFail(orig);
        if (res.ok && json.status === 'success') {
          form.style.display = 'none';
          if (done) { done.style.display = 'block'; done.focus(); }
          if (fail) fail.style.display = 'none';
          return;
        }
        if (json.status === 'fail' && json.data && typeof json.data === 'object') {
          const msgs = Object.keys(json.data).map((key) => {
            form.querySelector(`[name="${CSS.escape(key)}"]`)?.setAttribute('aria-invalid', 'true');
            return typeof json.data[key] === 'string' ? json.data[key] : '';
          }).filter(Boolean);
          return showFail(msgs.length ? msgs.join(' ') : orig);
        }
        showFail(orig);
      })
      .catch(() => { restore(); showFail(orig); });
  }, true);
})();
  • success (HTTP 2xx, status success): form hidden, .w-form-done shown.
  • fail (for example 422 validation): .w-form-fail shows the messages from data, matching fields get aria-invalid="true".
  • error, a response that is not JSON, or no network: .w-form-fail with its original Webflow text.
  • While sending, the button shows Webflow's waiting text (data-wait) and is disabled; a second submit is ignored.
  • During an active .sp session the script posts to the local api/action.php through sp.resolveLocalUrl, otherwise to PHP_URL. Put the Webflow staging host and the live domain on ALLOWED_ORIGINS.

Webflow's redirect setting, file upload fields and Webflow's spam protection are not handled by this script. Load it early (in the head) so it is active before a visitor can submit; if it does not load, Webflow handles the submit as before and the entry lands in Webflow's form submissions. A helper in @stagepass/modules is not part of this release: forms are site-specific, PHP is optional, and modules are front-end only.

Tested on 28 November 2026 with Webflow's published form script (jQuery 3.5.1 and webflow.js from a published Webflow site) in a headless browser against PHP 8.2: success, validation fail, HTTP 500, network error and double submit. The success path also ran through the loader, in production and in a .sp session. No request reached Webflow's form endpoint.

Security defaults

Unknown origins are never reflected in CORS headers. POST actions require a matching Origin. GET may omit it, but a present Origin still has to match. A filled honeypot field returns a generic success and does not run the handler. The rate limit is per IP and action, stored as files under .php/rate-limit/. Display of errors is off. Exception messages never go to the client.

In projects created with CLI 2.5.0, rate_limit_allows() refuses rate-limit storage faults unless APP_ENV is local, development, or dev (trimmed, any case). Every other value, including empty and unset, is HTTP 503, JSend error, Retry-After: 60, a log line, and no internals. Those three names stay fail-open with the same log. A failed flock is logged. A real limit hit stays HTTP 429. client_ip() reads X-Forwarded-For or RFC 7239 Forwarded only when REMOTE_ADDR is listed in TRUSTED_PROXIES. stagepass upgrade does not change api/. Copy the files from a new scaffold, or re-scaffold. CLI 2.4.1 and older stay fail-open and use only REMOTE_ADDR.

Local development and hosting

stagepass new, doctor, dev, and watch warn when PHP is missing, older than 8.2, or has no php-fpm or php-cgi. On macOS the hint is brew install php. The JavaScript build still runs. On a project with "php": true, dev and watch start Homebrew php-fpm (brew services start php, and brew services restart php only if start fails).

Prefer stagepass dev or the linked .sp domain. Caddy sets root * to the project path, then php_fastcgi 127.0.0.1:9000 and file_server. The public URL is https://your-project.sp/api/action.php.

stagepass build copies api/ to dist/api/ and .php/config.php to dist/.php/config.php. Since 2.4.1 it also copies a project-root .htaccess to dist/.htaccess when "php": true and the project has one. Upload dist/, the folder that contains api/, so the URL stays /api/action.php. The copy keeps .htaccess and .env.example. It skips .env, .php/.env, and .php/rate-limit/, plus logs, pid files, and key, certificate, or database files. A dist/.htaccess already on disk stays when the project has none. Watch does not copy PHP. FastCGI reads the project root, so edits show up on the next request.

That upload is the web root. .php/, including .php/config.php, is therefore public on Apache and nginx unless hidden paths are denied. Caddy already returns 404 for any path segment that starts with .. Published CLI 2.4.0 does not ship an Apache or nginx deny rule. Since 2.4.1 the PHP scaffold ships the Apache .htaccess below, and stagepass build copies it into dist/. stagepass upgrade writes that file when "php": true and the project root has none. It never overwrites an existing .htaccess. If the file has no RewriteRule "(^|/)\." - [F] line, upgrade prints a hint and still exits 0. nginx does not read .htaccess. Add the snippet below in the server block before location ~ \.php$. Prefer real environment variables so a .env file is not required in the web root. Projects created with 2.4.0 still need the rule until upgrade writes a missing .htaccess or you add it.

Apache, in the web root .htaccess. The host needs AllowOverride All and mod_rewrite. The rule follows HTML5 Boilerplate (file_access.conf), wrapped in IfModule:

Apache
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} "!(^|/)\.well-known/([^./]+./?)+$" [NC]
    RewriteCond %{SCRIPT_FILENAME} -d [OR]
    RewriteCond %{SCRIPT_FILENAME} -f
    RewriteRule "(^|/)\." - [F]
</IfModule>

nginx, inside the server block, before the PHP location ~ \.php$ block. If this location comes later, /.php/config.php can be passed to php-fpm. The rule follows HTML5 Boilerplate (security_file_access.conf):

nginx
location ~* /\.(?!well-known\/) {
    deny all;
}

Both rules were tested on 12 November 2026 on php:8.2-apache (AllowOverride All, a2enmod rewrite) and on nginx 1.27 with php:8.2-fpm. The results were the same on both servers. /.env, /.php/config.php, /api/.env.example, and /.git/HEAD returned HTTP 403, with no secret or config leak. /api/action.php?action=ping returned HTTP 200 and {"status":"success","data":{"pong":true},"message":null}. A file at /.well-known/test.txt returned HTTP 200, body well-known-ok. /.well-known/ as a directory with no index file returned HTTP 403 on both servers (no DirectoryIndex). Visible files under /.well-known/ stay reachable.

A quick check without Caddy, from the folder that contains api/ (the project root, or dist/ after a build):

Terminal
$ php -S 127.0.0.1:8080 -t .

That command serves /api/action.php. php -S 127.0.0.1:8080 -t api serves /action.php and does not match this layout. The published npm 2.4.0 package README already uses -t .. PHP's built-in server does not apply Caddy's hidden-path 404. Do not point php -S -t . at a folder that already contains a real .env. The package README has carried that php -S warning since 2.4.1. Published CLI 2.4.0 does not.

Existing projects

stagepass upgrade does not add the PHP boilerplate and does not replace api/action.php. Since 2.4.1, when stagepass.json has "php": true and the project root has no .htaccess, upgrade writes the shipped file (same bytes as stagepass new --php). An existing .htaccess is left unchanged. If it has no RewriteRule "(^|/)\." - [F] line, upgrade prints a hint, points at this page and api/README.md, and still exits 0. A symlink or directory named .htaccess is left in place. Projects without "php": true are unchanged. --dry-run writes nothing. Published CLI 2.4.0 does not write this file. Scaffold a throwaway project and copy the folders in, without overwriting files you already edited:

Terminal
$ stagepass new tmp --php --yes --no-link

Copy api/ and .php/ from tmp/ into the existing project. Or copy from the installed CLI templates, renaming api/env.example to api/.env.example and php-private/config.php to .php/config.php (npm pack drops dot paths). Set "php": true in stagepass.json, copy api/.env.example to .env, set ALLOWED_ORIGINS, and run stagepass link again so the Caddy block gets php_fastcgi.

If scripts/build.mjs is still an unmodified older scaffold, stagepass upgrade can replace it so the PHP copy step is included. An edited script stays as-is. Add the copy of api/, .php/config.php, and the project-root .htaccess into dist/ by hand. See CLI, PHP.

Projects created with published CLI 2.4.0 keep that version's api/action.php. An allowed OPTIONS preflight is HTTP 204 and still sends X-Powered-By. GET ping already omits it, because respond() calls header_remove and the OPTIONS path does not. Before http_response_code(204), insert the same lines 2.4.1 ships:

PHP
if (!headers_sent()) {
    header_remove('X-Powered-By');
}

Or set expose_php = Off in php.ini. expose_php is PHP_INI_SYSTEM. php_flag expose_php off in .htaccess does not change it. In the same file, php_flag display_errors off does apply, because display_errors is PHP_INI_ALL. ini_set('expose_php', '0') returns false and leaves the value On. Verified 13 November 2026 on php:8.2-apache with AllowOverride All and a2enmod rewrite. OPTIONS with Origin https://your-project.sp was HTTP 204 without X-Powered-By, and ping stayed HTTP 200.

Limits of this starter

No mail, no database layer, and no framework. Keep actions small. Put shared checks in api/lib/validate.php only when several actions need them. This is a front controller, not a general-purpose CMS backend.

Command flags and the Caddy version check are on the CLI page.