Reference documentation and code samples for the Cloud Datastore Client class DatastoreSessionHandler.
Custom session handler backed by Cloud Datastore.
Instead of storing the session data in a local file, this handler stores the
data in Cloud Datastore. The biggest benefit of doing this is the data can be
shared by multiple instances, making it suitable for cloud applications.
The downside of using Cloud Datastore is that write operations will cost you
some money, so it is highly recommended to minimize the write operations
while using this handler. In order to do so, keep the data in the session as
limited as possible; for example, it is ok to put only signed-in state and
the user id in the session with this handler. However, for example, it is
definitely not recommended that you store your application's whole undo
history in the session, because every user operation will cause a Datastore
write, potentially costing you a lot of money.
This handler doesn't provide pessimistic lock for session data. Instead, it
uses Datastore Transaction for data consistency. This means that if
multiple requests are modifying the same session data simultaneously, there
will be more probablity that some of thewriteoperations will fail.
If you are building an ajax application which may issue multiple requests
to the server, please design your session data carefully in order to avoid
possible data contentions. Also please see the 2nd example below for how to
properly handle errors onwriteoperations.
The handler sets the Datastore namespace to the value of session.save_path,
isolating the session data from your application data, it also uses the
session.name as the Datastore kind, and the session id as the Datastore id.
By default, it does nothing on gc for reducing the cost. Pass positive value
up to 1000 for $gcLimit parameter to delete entities in gc.
Note: The datastore transaction only lasts 60 seconds. If this handler is
used for long running requests, it will fail onwrite.
The first example automatically writes the session data. It's handy, but
the code doesn't stop even if it fails to write the session data, because
thewritehappens when the code exits. If you want to know whether the
session data is correctly written to the Datastore, you need to callsession_write_close()explicitly and then handleE_USER_WARNINGproperly. See the second example for a demonstration.
Example:
use Google\Cloud\Datastore\DatastoreClient;
use Google\Cloud\Datastore\DatastoreSessionHandler;
$datastore = new DatastoreClient();
$handler = new DatastoreSessionHandler($datastore);
session_set_save_handler($handler, true);
session_save_path('sessions');
session_start();
// Then write and read the $_SESSION array.
$_SESSION['name'] = 'Bob';
echo $_SESSION['name'];
// Session Handler with Error Handling
use Google\Cloud\Datastore\DatastoreClient;
use Google\Cloud\Datastore\DatastoreSessionHandler;
$datastore = new DatastoreClient();
$handler = new DatastoreSessionHandler($datastore);
session_set_save_handler($handler, true);
session_save_path('sessions');
session_start();
// Then read and write the $_SESSION array.
$_SESSION['name'] = 'Bob';
function handle_session_error($errNo, $errStr, $errFile, $errLine) {
// We throw an exception here, but you can do whatever you need.
throw new RuntimeException("$errStr in $errFile on line $errLine", $errNo);
}
set_error_handler('handle_session_error', E_USER_WARNING);
// If `write` fails for any reason, an exception will be thrown.
session_write_close();
restore_error_handler();
// You can still read the $_SESSION array after closing the session.
echo $_SESSION['name'];
Namespace
Google \ Cloud \ Datastore
Methods
__construct
Create a custom session handler backed by Cloud Datastore.
[optional] A number of entities to delete in the
garbage collection. Defaults to 0 which means it does nothing.
The value larger than 1000 will be cut down to 1000.
options
array
Configuration Options
↳ entityOptions
array
Default options to be passed to theDatastoreClient::entity()method when writing session data to Datastore. If not specified, defaults to['excludeFromIndexes' => ['data']].
↳ databaseId
string
ID of the database to which the entities belong.
open
Start a session, by creating a transaction for the laterwrite.
Parameters
Name
Description
savePath
string
The value ofsession.save_pathsetting will be
used here. It will use this value as the Datastore namespaceId.
sessionName
string
The value ofsession.namesetting will be
used here. It will use this value as the Datastore kind.
Returns
Type
Description
bool
close
Just return true for this implementation.
read
Read the session data from Cloud Datastore.
Parameter
Name
Description
id
mixed
write
Write the session data to Cloud Datastore.
Parameters
Name
Description
id
string
Identifier used to construct aKeyfor theEntityto be written.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[],[],null,["# Cloud Datastore Client - Class DatastoreSessionHandler (1.33.1)\n\nVersion latestkeyboard_arrow_down\n\n- [1.33.1 (latest)](/php/docs/reference/cloud-datastore/latest/DatastoreSessionHandler)\n- [1.33.0](/php/docs/reference/cloud-datastore/1.33.0/DatastoreSessionHandler)\n- [1.32.3](/php/docs/reference/cloud-datastore/1.32.3/DatastoreSessionHandler)\n- [1.31.0](/php/docs/reference/cloud-datastore/1.31.0/DatastoreSessionHandler)\n- [1.30.0](/php/docs/reference/cloud-datastore/1.30.0/DatastoreSessionHandler)\n- [1.29.2](/php/docs/reference/cloud-datastore/1.29.2/DatastoreSessionHandler)\n- [1.28.2](/php/docs/reference/cloud-datastore/1.28.2/DatastoreSessionHandler)\n- [1.26.0](/php/docs/reference/cloud-datastore/1.26.0/DatastoreSessionHandler)\n- [1.25.0](/php/docs/reference/cloud-datastore/1.25.0/DatastoreSessionHandler)\n- [1.24.4](/php/docs/reference/cloud-datastore/1.24.4/DatastoreSessionHandler)\n- [1.23.0](/php/docs/reference/cloud-datastore/1.23.0/DatastoreSessionHandler)\n- [1.22.1](/php/docs/reference/cloud-datastore/1.22.1/DatastoreSessionHandler)\n- [1.21.2](/php/docs/reference/cloud-datastore/1.21.2/DatastoreSessionHandler)\n- [1.19.0](/php/docs/reference/cloud-datastore/1.19.0/DatastoreSessionHandler)\n- [1.18.1](/php/docs/reference/cloud-datastore/1.18.1/DatastoreSessionHandler)\n- [1.17.1](/php/docs/reference/cloud-datastore/1.17.1/DatastoreSessionHandler) \nReference documentation and code samples for the Cloud Datastore Client class DatastoreSessionHandler.\n\nCustom session handler backed by Cloud Datastore.\n\nInstead of storing the session data in a local file, this handler stores the\ndata in Cloud Datastore. The biggest benefit of doing this is the data can be\nshared by multiple instances, making it suitable for cloud applications.\n\nThe downside of using Cloud Datastore is that write operations will cost you\nsome money, so it is highly recommended to minimize the write operations\nwhile using this handler. In order to do so, keep the data in the session as\nlimited as possible; for example, it is ok to put only signed-in state and\nthe user id in the session with this handler. However, for example, it is\ndefinitely not recommended that you store your application's whole undo\nhistory in the session, because every user operation will cause a Datastore\nwrite, potentially costing you a lot of money.\n\nThis handler doesn't provide pessimistic lock for session data. Instead, it\nuses Datastore Transaction for data consistency. This means that if\nmultiple requests are modifying the same session data simultaneously, there\nwill be more probablity that some of the `write` operations will fail.\n\nIf you are building an ajax application which may issue multiple requests\nto the server, please design your session data carefully in order to avoid\npossible data contentions. Also please see the 2nd example below for how to\nproperly handle errors on `write` operations.\n\nThe handler sets the Datastore namespace to the value of session.save_path,\nisolating the session data from your application data, it also uses the\nsession.name as the Datastore kind, and the session id as the Datastore id.\nBy default, it does nothing on gc for reducing the cost. Pass positive value\nup to 1000 for $gcLimit parameter to delete entities in gc.\n\nNote: The datastore transaction only lasts 60 seconds. If this handler is\nused for long running requests, it will fail on `write`.\n\nThe first example automatically writes the session data. It's handy, but\nthe code doesn't stop even if it fails to write the session data, because\nthe `write` happens when the code exits. If you want to know whether the\nsession data is correctly written to the Datastore, you need to call\n`session_write_close()` explicitly and then handle `E_USER_WARNING`\nproperly. See the second example for a demonstration.\n\nExample: \n\n use Google\\Cloud\\Datastore\\DatastoreClient;\n use Google\\Cloud\\Datastore\\DatastoreSessionHandler;\n\n $datastore = new DatastoreClient();\n\n $handler = new DatastoreSessionHandler($datastore);\n\n session_set_save_handler($handler, true);\n session_save_path('sessions');\n session_start();\n\n // Then write and read the $_SESSION array.\n $_SESSION['name'] = 'Bob';\n echo $_SESSION['name'];\n\n // Session Handler with Error Handling\n use Google\\Cloud\\Datastore\\DatastoreClient;\n use Google\\Cloud\\Datastore\\DatastoreSessionHandler;\n\n $datastore = new DatastoreClient();\n\n $handler = new DatastoreSessionHandler($datastore);\n session_set_save_handler($handler, true);\n session_save_path('sessions');\n session_start();\n\n // Then read and write the $_SESSION array.\n $_SESSION['name'] = 'Bob';\n\n function handle_session_error($errNo, $errStr, $errFile, $errLine) {\n // We throw an exception here, but you can do whatever you need.\n throw new RuntimeException(\"$errStr in $errFile on line $errLine\", $errNo);\n }\n\n set_error_handler('handle_session_error', E_USER_WARNING);\n // If `write` fails for any reason, an exception will be thrown.\n session_write_close();\n restore_error_handler();\n\n // You can still read the $_SESSION array after closing the session.\n echo $_SESSION['name'];\n\nNamespace\n---------\n\nGoogle \\\\ Cloud \\\\ Datastore\n\nMethods\n-------\n\n### __construct\n\nCreate a custom session handler backed by Cloud Datastore.\n\n### open\n\nStart a session, by creating a transaction for the later `write`.\n\n### close\n\nJust return true for this implementation.\n\n### read\n\nRead the session data from Cloud Datastore.\n\n### write\n\nWrite the session data to Cloud Datastore.\n\n### destroy\n\nDelete the session data from Cloud Datastore.\n\n### gc\n\nDelete the old session data from Cloud Datastore.\n\nConstants\n---------\n\n### DEFAULT_GC_LIMIT\n\n Value: 0\n\n### NAMESPACE_ALLOWED_PATTERN\n\n Value: '/^[A-Za-z\\d\\.\\-_]{0,100}$/'\n\n### NAMESPACE_RESERVED_PATTERN\n\n Value: '/^__.*__$/'"]]