# Add e-signatures and clickwrap to PHP

> Add e-signatures and clickwrap to plain PHP with the curl extension: POST /v1/sessions, GET /v1/records, getenv() and $\_SESSION. No Composer package needed.

Source: https://esigncomply.com/php

Stack · PHP

To add e-signatures and clickwrap to PHP, call the REST API: there is no PHP package, because the server SDK exists for Node.js only. The curl extension sends `POST /v1/sessions` and `GET /v1/records/{id}` with the secret key, `$_SESSION` holds the pinned versions, and the browser SDK from a script tag attaches to your own form. Esign Comply seals each acceptance.

Follow the quickstart and each signature is a valid electronic signature under the U.S. ESIGN Act, state UETA laws and New York's ESRA, and each clickwrap is built the way courts require: clear notice of the terms, an unmistakable act of assent, and a sealed record of both.

[Get an API key](https://esigncomply.com/signup) · [Read the docs](https://esigncomply.com/docs/quickstart/php)

No package to install: PHP's curl extension is enough

[PHP quickstart](https://esigncomply.com/docs/quickstart/php)

Free plan: 10 live signatures a month and a full test mode. No card required.

Last updated November 26, 2026

Run in PHP before publishing

**The API call**

src/esigncomply.php (excerpt)

```php
function esc(string $method, string $path, ?array $body = null, ?string $idempotencyKey = null): array
{
    $headers = ['Authorization: Bearer ' . API_KEY, 'Accept: application/json'];
    if ($body !== null) {
        $headers[] = 'Content-Type: application/json';
    }
    if ($idempotencyKey !== null) {
        $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
    }

    $curl = curl_init(API_URL . $path);
    curl_setopt_array($curl, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true, // hand the answer back: without it curl prints the answer into your page
        CURLOPT_TIMEOUT => 10,
    ]);
    if ($body !== null) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body));
    }
    for ($attempt = 1; ; $attempt++) {
        $answer = curl_exec($curl);
        if ($answer === false) {
            return [0, ['error' => ['code' => 'network_error', 'message' => curl_error($curl)]]];
        }
        // curl does not fail on 4xx and 5xx: the status is here, and the error envelope is the body.
        $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
        if ($status !== 429 || $attempt === 3) {
            return [$status, json_decode($answer, true) ?? []];
        }
        // Rate limited: wait for the seconds in Retry-After, 1 at least and 5 at most, and send it again, twice at most.
        sleep(max(1, min((int) curl_getinfo($curl, CURLINFO_RETRY_AFTER), 5)));
    }
}
```

**Create the session**

public/index.php (excerpt)

```php
// Step 4: create the session with the secret key. The browser gets the client token only.
if ($method === 'POST' && $path === '/api/ceremony') {
    // The page that runs the ceremony: the origin the browser reports, plus its path.
    $origin = $_SERVER['HTTP_ORIGIN'] ?? 'http://' . $_SERVER['HTTP_HOST'];
    [$status, $session] = esc('POST', '/sessions', [
        'profile' => getenv('ESIGNCOMPLY_PROFILE_ID'),
        'signer' => SIGNER,
        'documents' => [
            ['document' => DOCUMENTS['terms'], 'version' => 'current'],
            ['document' => DOCUMENTS['privacy'], 'version' => 'current'],
        ],
        'context' => ['url' => $origin . '/signup', 'locale' => 'en-US', 'purpose' => 'account_signup'],
    ], 'signup-' . SIGNER['external_id'] . '-' . bin2hex(random_bytes(16)));
    if ($status !== 201) {
        send_json(502, ['error' => $session['error']['code'] ?? 'unknown']);
        return;
    }

    signup_session();
    $_SESSION['signer_id'] = SIGNER['external_id'];
    $_SESSION['version_ids'] = array_column($session['documents'], 'version_id');
    session_write_close();
    send_json(200, ['clientToken' => $session['client_token'], 'apiUrl' => $session['api_url'], 'documents' => $session['documents']]);
```

**Confirm**

public/index.php (excerpt)

```php
// Step 6: confirm the record with the secret key before the account exists.
if ($method === 'POST' && $path === '/api/signup/confirm') {
    $body = json_decode((string) file_get_contents('php://input'), true); // an empty or malformed body is refused below
    $recordId = is_array($body) && is_string($body['recordId'] ?? null) ? $body['recordId'] : 'missing';
    signup_session(readOnly: true);
    [$status, $record] = esc('GET', '/records/' . rawurlencode($recordId));

    $versions = array_column($record['documents'] ?? [], 'version_id');
    $expected = $_SESSION['version_ids'] ?? [];
    sort($versions);
    sort($expected);
    $confirmed = $status === 200
        && in_array($record['status'], SEALED, true)
        && $record['livemode'] === LIVE
        && $record['signer']['external_id'] === ($_SESSION['signer_id'] ?? null)
        && $versions === $expected;

    error_log($confirmed ? "confirmed {$record['id']} ({$record['status']})" : 'refused');
    if (!$confirmed) {
        send_json(409, ['confirmed' => false]);
        return;
    }
    // Only now create the account, and store $record['id'] and $record['receipt'] with it.
    send_json(200, ['confirmed' => true, 'recordId' => $record['id']]);
```

**Session**

src/esigncomply.php (excerpt)

```php
// Server-owned state: PHP's own session. The data stays in a file on the server,
// and the browser holds only the session ID in a cookie.
function signup_session(bool $readOnly = false): void
{
    session_start([
        'cookie_httponly' => true,
        'cookie_samesite' => 'Lax',
        'cookie_secure' => LIVE, // HTTPS only, in production
        'use_strict_mode' => true,
        // A session is locked while it is open. The confirm route only reads it, so it closes it at once.
        'read_and_close' => $readOnly,
    ]);
}
```

Integrate with PHP

## How do you integrate Esign Comply with PHP?

In plain PHP the integration is three files: a client function on the curl extension, a front controller in `public/` that answers four addresses, and the page. The key is read with `getenv()`, the pinned versions live in `$_SESSION`, and everything except `public/` stays outside the document root.

PHP is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

Source: [PHP Manual, Introduction](https://www.php.net/manual/en/introduction.php), read on November 26, 2026.

[PHP quickstart](https://esigncomply.com/docs/quickstart/php) · [All stacks](https://esigncomply.com/stacks)

Where each part lives in PHP

- **The API call** · `src/esigncomply.php`
- **Create the session** · `public/index.php`
- **Confirm** · `public/index.php`
- **Session** · `src/esigncomply.php`

Run on 2026-11-26 with PHP 8.5.13 and its curl extension (cURL 8.23.0), no framework and no Composer package, under PHP's built-in web server with a router script (in the official Composer container image), with the browser SDK script build and the conformance check from esigncomply 1.0.4, against the API in test mode.

Copy-paste prompt

## What prompt adds Esign Comply clickwrap to a PHP app?

Paste this into Cursor, Claude Code or the AI coding tool that is open on your project. It names the packages that exist, where the secret key goes in PHP, what to build and what never to do, and it ends with the rules block for your project.

The rules block lives at [/rules.md](https://esigncomply.com/rules.md). Added to your project's instruction file, it makes every later session build signing and acceptance flows the same way. The [prompt generator](https://esigncomply.com/product/prompt-generator) writes the long version, with your own document and profile IDs.

[Pages for each AI tool](https://esigncomply.com/build)

Prompt: Esign Comply clickwrap in PHP

```php
Add Esign Comply clickwrap to my PHP app: a signup form where the user accepts the Terms of Service and the Privacy Notice with a checkbox and a button.

Read these first and follow them exactly. If something conflicts with existing code, or you are unsure how to implement a step, stop and ask. Do not invent API methods, packages or legal wording.
- https://esigncomply.com/docs/quickstart/php.md (the steps and the tested code for PHP)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

PHP facts
- There is no Esign Comply package for PHP. Do not install or invent one. The server calls the REST API at https://esigncomply.com/v1 with Authorization: Bearer and the secret key, using the curl extension or the HTTP client the project already has.
- The browser SDK is a script tag: https://esigncomply.com/sdk/v1/esigncomply.js. It defines the global EsignComply.
- The secret key is in the environment variable ESIGNCOMPLY_API_KEY. PHP does not read .env files on its own. Read it with getenv(): $_ENV is empty when variables_order has no "E", as in php.ini-development and php.ini-production. Never print the key.
- Keep .env and every PHP file except the front controller outside the document root. Only public/ is served.
- With curl, set CURLOPT_RETURNTRANSFER, or curl prints the API's answer into the page. curl does not fail on 4xx and 5xx: read the status with curl_getinfo and the error envelope from the body. Do not call curl_close: it is deprecated since PHP 8.5.
- Keep the signer ID and the pinned version IDs in $_SESSION. Start the session with cookie_httponly, cookie_samesite and use_strict_mode. A session is locked while it is open: open it with read_and_close in the route that only reads it, and never keep it open across the API call.
- Print the document HTML as it is. Escape everything else you print with htmlspecialchars.
- The page is on screen before the script has a session: render the checkbox disabled and enable it when observeAssent has resolved.

Build
1. Verify the key: GET /v1/usage with ESIGNCOMPLY_API_KEY. Stop if it fails.
2. Register the Terms of Service and the Privacy Notice as documents and publish one version of each from the documents in this project. If the project has none, register short sample documents and say so in your report. Never write or change the wording of the real documents. Create a profile: jurisdictions ["US-FED"], method "checkbox", assurance_level "L1".
3. Server: POST /api/ceremony calls POST /v1/sessions with an Idempotency-Key, saves the signer ID and the pinned version IDs in $_SESSION, and returns only clientToken, apiUrl and documents.
4. Server: GET /legal/terms and /legal/privacy render the html from GET /v1/documents/{id}/versions/{version_id}/content inside <article data-esc-document>, unmodified.
5. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click.
6. Server: POST /api/signup/confirm calls GET /v1/records/{id} and requires: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in $_SESSION. Only then create the account.

Never
- Never pre-check the box, auto-submit, or call .click() on the user's behalf.
- Never use "By continuing" or "By clicking below" wording. The notice names the button by its label and each document by its registered name.
- Never put the secret key, or any call that uses it, in code that reaches the browser.
- Never show "signed" or "accepted" before the server has confirmed the record.
- Never fall back to an acceptance with no record when a session is refused.

Check before you report success
- Run: npx esigncomply check --url http://localhost:8000/signup --callback http://localhost:8000/api/signup/confirm
  Fix every finding marked "block". List every finding marked "warn".
- Report the files you created or changed, anything you did not implement and why, and the conformance summary.

Then add the rules block to this project's instruction file: https://esigncomply.com/rules.md
```

3 things to watch

## What goes wrong when you add e-signatures in PHP?

These are specific to PHP. Each one was seen while the quickstart's code was run, or is in PHP's own documentation.

- **The built-in server hands out .env when the project folder is the document root**

  PHP's manual says requests are served from the folder PHP was started in unless `-t` names a document root. In the test on PHP 8.5.13, with the server started in the project folder, `GET /.env` was answered `200` with the whole file, the key included. With `-t public` it was answered `404`.

  Source: [PHP Manual, Built-in web server](https://www.php.net/manual/en/features.commandline.webserver.php), read on November 26, 2026.

- **$\_ENV is empty under both php.ini files that PHP ships**

  PHP fills `$_ENV` only when `variables_order` contains an `E`. The built-in default is `EGPCS`, and `php.ini-development` and `php.ini-production` of PHP 8.5.13 both set `GPCS`. In the test with `GPCS`, `$_ENV` did not hold the key and `getenv()` returned it. The quickstart reads every variable with `getenv()`.

  Source: [PHP Manual, Description of core php.ini directives](https://www.php.net/manual/en/ini.core.php), read on November 26, 2026.

- **A session is locked for as long as a request keeps it open**

  PHP's manual says session data is locked by default to avoid race conditions. In the test with four workers, a request that kept the session open for two seconds made a second request with the same cookie wait 1.7 seconds in `session_start()`. The confirm route opens the session with `read_and_close` before it calls the API.

  Source: [PHP Manual, Session Management Basics](https://www.php.net/manual/en/features.session.security.management.php), read on November 26, 2026.

## Where are the PHP quickstart and the API reference?

Start with the quickstart: it carries every file this page excerpts, in the order you write them.

- Quickstart

  **[PHP quickstart](https://esigncomply.com/docs/quickstart/php)**

  Step by step, from install to your first sealed test record, with every file and the output of each step.

- Reference

  **[API reference](https://esigncomply.com/docs/api)**

  Every endpoint, field and error code. Sessions, records and documents are the three this page uses.

- Guide

  **[Server confirmation](https://esigncomply.com/docs/guides/server-confirmation)**

  The one place access is granted: what to compare, and the webhook that backs the check up.

Verifiable

## What does Esign Comply record for a signature in PHP?

The same record on every stack and platform. Your PHP code creates the session and confirms the record, and the browser SDK reports what happened on the page. Esign Comply seals the result where your code cannot change it. The record itself is described on [Evidence and verification](https://esigncomply.com/product/evidence).

- **Observed and asserted fields**

  Every field is tagged. Observed is what the browser SDK and the API saw: the box unchecked at load, the tick from a trusted user event, the notice text, the terms version by hash, the server time. Asserted is what your app said, such as the user's email.

- **A signed receipt**

  `complete()` returns a receipt signed with ES256, using keys you do not hold. Your server stores it next to the user, and `GET /v1/records/{id}/receipt` returns it again.

- **An external timestamp**

  An outside authority timestamps the hash of every live record (RFC 3161), so the time on the record does not rest on your clock or on ours.

- **An offline verifier**

  Each record has an evidence report (PDF) and an evidence package (ZIP). Anyone you send the package to checks the acceptance with the open-source `esigncomply-verify`, without an account.

[How sealing and verification work](https://esigncomply.com/product/evidence) · [Observed and asserted, in the docs](https://esigncomply.com/docs/concepts/observed-and-asserted) · [The offline verifier](https://esigncomply.com/docs/sdk/verify)

Record

`rec_Z4m8`

simple · L1

Recorded

Written durably, receipt signed with ES256

Timestamped

External RFC 3161 token over the record hash

Anchored

Public anchor pending

Checkbox changed by a trusted user event · observed

Terms of Service, version dv_3kT9 · observed

Server time 2026-11-21T15:03:20.291Z · observed

Signer email dana@example.org · asserted

record_hash sha256:5be7… · example record

## Questions about e-signatures in PHP

### Is there an Esign Comply SDK for PHP?

No. The server SDK exists for Node.js only. A PHP server calls the REST API directly with the secret key, and the quickstart does it with the curl extension that PHP ships, with no Composer package. The browser side is the same SDK as on every stack.

### Where do I create the session in PHP?

In the front controller, in the branch that answers `POST /api/ceremony`, with a `POST` to `/v1/sessions` that carries the secret key and an `Idempotency-Key`. It saves the pinned versions in `$_SESSION` and returns only the client token, the API URL and the documents.

### Can PHP's built-in server run this in production?

No. PHP's manual says the built-in server is designed to aid application development, should not be used on a public network, and runs one single-threaded process. The quickstart was run under it only, with `public/index.php` as the router script. Deploy the same front controller under the web server you run.

### Should the curl code call curl_close()?

No. On PHP 8.5.13 the call printed `Function curl_close() is deprecated since 8.5` into the answer of the route. The quickstart leaves it out and sets `CURLOPT_RETURNTRANSFER`: without that option curl printed the API's whole answer into the response in the test.

### Where does PHP keep the pinned versions?

In a session file on the server. In the test it was a file named `sess_` plus the ID in `/tmp`, readable by its owner only, and the browser held a 32-character ID in an `HttpOnly` cookie. With more than one machine, keep the pinned versions in your database.

### Other stacks

- [Laravel](https://esigncomply.com/laravel)
- [Python](https://esigncomply.com/python)
- [Go](https://esigncomply.com/go)

### Platforms used with PHP

- [Railway](https://esigncomply.com/railway)
- [Render](https://esigncomply.com/render)
- [Fly.io](https://esigncomply.com/fly-io)

[All stacks](https://esigncomply.com/stacks) · [All platforms](https://esigncomply.com/platforms) · [Clickwrap API](https://esigncomply.com/clickwrap) · [E-signature API](https://esigncomply.com/sign)

## Call the API from the PHP you already run. Leave the record to us.

[Get an API key](https://esigncomply.com/signup) · [Read the docs](https://esigncomply.com/docs/quickstart/php)

Free plan: 10 live signatures a month and a full test mode. No card required.

PHP is a trademark of its owner. Esign Comply is not affiliated with it. What this page says about PHP is from PHP's documentation or from a test run, as marked, on November 26, 2026. `/php.md` is this page as Markdown.

---

Every page on esigncomply.com has a Markdown version at the same URL plus `.md` (the home page is `https://esigncomply.com/index.md`). https://esigncomply.com/llms.txt lists them.

---

Esign Comply is the e-signature API and clickwrap API for developers who build their own signing flow in their own UI: it supplies the ceremony rules as a generated prompt for AI coding tools, records events in direct browser ceremonies, and seals independent, verifiable evidence.
