Connect a PHP App to ONLYOFFICE Docs and Save Edits

A custom PHP application integrates with ONLYOFFICE Docs by serving a document URL that Docs can fetch, loading the Docs JavaScript API in the browser, and accepting a callback that stores the edited file. Keep JWT signing on the PHP server, and make both the document URL and callback URL reachable from the network where ONLYOFFICE Docs runs.

Many integration failures come from mixing up the addresses seen by the browser, PHP, and Document Server. Test each route from the network that uses it.

Prepare the PHP app and Document Server

ONLYOFFICE Docs provides the document editor. Your application remains the document manager and storage service: it authenticates users, decides which files they may open, supplies the source file, and saves the result. Install Document Server separately, then verify its /healthcheck endpoint before debugging application code.

Use three reachable addresses in your configuration:

  • Docs URL: the address the user’s browser uses to load the editor and its JavaScript API.
  • Document URL: an absolute address the Document Server can use to download the source file from PHP storage.
  • Callback URL: an absolute address the Document Server can POST to after editing so PHP can store changes.
A custom PHP Project files page showing a DOCX file and the ONLYOFFICE editor embedded beneath it.
Illustrative app screen: the PHP application owns the file list while the ONLYOFFICE editor opens inside its page.

For example, https://docs.example.com can serve the editor, while https://app.example.com/files/42/download and https://app.example.com/onlyoffice/callback point to PHP. Test browser-to-Docs and Docs-to-PHP reachability. In deployment, localhost means the current machine or container, so it is usually the wrong cross-service address.

Build a document configuration for an authorized file

For an authenticated open request, load the file’s metadata and build the editor configuration on the PHP backend. Set the file extension, title, absolute download URL, and a document key. Keep that key stable for concurrent editors of the same version; change it when PHP replaces the source with a new version.

<?php
$config = [
  'documentType' => 'word',
  'document' => [
    'fileType' => 'docx',
    'key' => $document['revision_key'],
    'title' => $document['name'],
    'url' => 'https://app.example.com/files/42/download',
    'permissions' => ['edit' => true],
  ],
  'editorConfig' => [
    'callbackUrl' => 'https://app.example.com/onlyoffice/callback',
    'user' => ['id' => (string)$user['id'], 'name' => $user['name']],
  ],
];
A PHP config.php code view with document fileType, key, title, URL, and editorConfig callbackUrl values.
Illustrative PHP configuration: the document URL and callback URL connect storage to the editor.

Enforce file permissions before generating the URL. Do not expose storage credentials or bypass authorization; private or local links may also require a token under ONLYOFFICE’s rules.

See ONLYOFFICE’s document configuration reference and self-hosted installation guide for required fields and the API script path.

Load the editor and sign its configuration

JWT means JSON Web Token, a signed token that lets ONLYOFFICE verify the configuration was not changed in transit. JWT validation is enabled by default in current deployments; sign the editor config with the matching browser-token secret configured in Docs. If your setup uses a separate outgoing-token secret, validate callbacks with that outbox secret too. Starting with Docs 7.2, Docker installations can generate a secret automatically, so set and retain stable secrets for production.

The official ONLYOFFICE signature guide shows PHP code with the maintained firebase/php-jwt package. Install it with composer require firebase/php-jwt, then sign the complete configuration on the backend before returning it to the page:

use Firebase\JWT\JWT;

$secret = getenv('ONLYOFFICE_JWT_SECRET');
if (!$secret) {
    throw new RuntimeException('ONLYOFFICE JWT secret is not configured');
}
$config['token'] = JWT::encode($config, $secret, 'HS256');
A PHP sign.php code view reading ONLYOFFICE_JWT_SECRET from the environment and signing the config with HS256.
Illustrative backend code: the server signs the editor configuration without exposing the JWT secret in the browser.

Keep the secret out of browser code and source control. Load https://docs.example.com/web-apps/apps/api/documents/api.js and pass the signed JSON to DocsAPI.DocEditor:

<div id="editor"></div>
<script src="https://docs.example.com/web-apps/apps/api/documents/api.js"></script>
<script>
  new DocsAPI.DocEditor("editor", <?= $signedConfigJson ?>);
</script>

Encode JSON safely with json_encode or fetch the signed config from a same-origin endpoint; do not concatenate untrusted values into JavaScript. The signature guide documents HMAC-SHA256. For load-balanced Docs 8.1 and later, the API script can include the documented shardkey query parameter; a single server does not need it.

Save changes through a PHP callback

After editing, Document Server sends a POST request to callbackUrl. Status 2 means editing is complete and the file is ready to save; status 6 is a force-save result. The callback includes a temporary download URL for the edited file. Download it and atomically replace the stored version, or create a new version according to your app’s revision policy. Return {"error":0} only after your storage write succeeds.

<?php
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$raw = file_get_contents('php://input');
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
$auth = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$token = preg_replace('/^Bearer\s+/i', '', $auth);
$claims = JWT::decode($token, new Key($outboxSecret, 'HS256'));
$verified = (array)($claims->payload ?? []);

if (($verified['key'] ?? '') !== ($data['key'] ?? '')) {
    http_response_code(401);
    exit;
}
$document = findDocumentByRevisionKey($verified['key']);
if (!$document) {
    http_response_code(404);
    exit;
}
if (in_array((int)$data['status'], [2, 6], true)) {
    downloadAndStoreFromDocs($data['url'], $document);
}
header('Content-Type: application/json');
echo json_encode(['error' => 0]);
A PHP callback.php code view handling edit statuses 2 and 6 and returning a JSON error value of zero.
Illustrative callback logic: save the returned document for supported save statuses and acknowledge successful processing.

The example assumes the default outgoing Authorization: Bearer JWT header and matching outbox secret. Adapt it if your server uses a different header or body token. The download helper should allow only your Docs host, check the response, and safely replace the expected file. Never trust an arbitrary URL or an unsigned document key.

After a successful save, return JSON containing {"error":0}. Consult the callback reference for statuses and payloads, and the save lifecycle for callback timing.

Verify the complete round trip

Open a test DOCX as an authorized user, make a small edit, and close the editor. Confirm the callback key and status match the intended file, verify your app stored the new bytes, then reopen the document. If loading fails, check the API script route and config token; if saving fails, check callback reachability, JWT validation, the JSON response, and PHP storage logs.

ONLYOFFICE publishes a PHP integration example and a PHP sample app, but explicitly warns that sample integrations lack production protections such as storage authorization and save-request validation. Use them to understand the API flow, then retain your own application’s access checks and callback security.

Leave a Comment

Clear Nextcloud’s File Locking Warning with Redis

Enable reliable Nextcloud file locking, choose the right Redis or Valkey backend, and verify the warning clears without risking concurrent file changes.

What It Takes to Target an A+ Nextcloud Security Rating

What It Takes to Target an A+ Nextcloud Security Rating

Fix common Nextcloud scan findings with current updates, HTTPS and HSTS, precise reverse-proxy trust, and checks against the public server.

Automate Consistent Nextcloud Backups with Restic and Cron

Automate Consistent Nextcloud Backups with Restic and Cron

Back up Nextcloud’s files and MariaDB together, schedule encrypted Restic snapshots with cron, and verify recovery without risking the live server.

Enable Nextcloud Server-Side Encryption with Measured Impact

Configure Nextcloud SSE for the storage that needs it, protect encryption keys, and measure transfer and CPU impact before encrypting existing files.

Add Elasticsearch Full-Text Search to Nextcloud

Connect Nextcloud’s file search to Elasticsearch, index document contents, and choose a setup that fits your server and security needs.

Set a Reliable Expiration Policy for Nextcloud Deleted Files

Set a Reliable Expiration Policy for Nextcloud Deleted Files

Configure Nextcloud to remove deleted files after a defined retention period, schedule background jobs reliably, and avoid commands that purge every user’s trash.

Clear Nextcloud’s Missing Database Indexes Warning

Clear Nextcloud’s Missing Database Indexes Warning

Run Nextcloud’s OCC repair safely, preview the database changes, and check why the warning might remain.

Raise Nextcloud’s Web Upload Limit Past 2 GB

Raise Nextcloud’s Web Upload Limit Past 2 GB

Allow larger Nextcloud browser uploads by aligning PHP, Nginx or Apache, temporary storage, and timeout settings—and verify which limit is blocking the file.

Clear Nextcloud’s PHP Memory Warning at the Web Server

Set the PHP memory limit Nextcloud actually uses, restart the right service, and confirm the 512 MB setting in Admin Overview.

Connect an S3-Compatible Bucket to Nextcloud External Storage

Mount a compatible object-storage bucket in Nextcloud using its S3 backend, with the right endpoint, credentials, access scope, and verification steps.