# PHP

_Encrypt data server-side, invoke Functions, Enclaves and proxy requests through Relay._

> Encrypting/Decrypting data with our backend SDKs may expose you to greater
>   compliance burden because your server needs to handle plaintext data. Instead,
>   we recommend using [Relay](/relay) or our [Client-Side SDKs](/sdks) to encrypt
>   data.

## Getting started

### Dependencies

> The Evervault SDK requires PHP 7.1.0 or later.

The bindings also require the following extensions; `openssl`, `curl`, `json`, and `mbstring`.

If you install the bindings using Composer, these should automatically be installed. Otherwise, ensure that the extensions are available on your system.

### Install the SDK

Our PHP SDK is distributed via [Composer](https://getcomposer.org/), or it can be installed manually.

### Initialize the SDK

The SDK needs to be initialized with an App's ID and API key. If you don't have one yet, you can get one by creating an App in the [Evervault Dashboard](https://app.evervault.com).

```php
<?php
use \Evervault\Evervault;

$evervault = new Evervault('<APP_ID>', '<API_KEY>');
```

### Encrypt a string

Now that the SDK is initialized, we can encrypt a string.

```php
$encrypted = $evervault->encrypt('Hello, world!');
```

## Reference

### encrypt()

Encrypts data using [Evervault Encryption](/developers/evervault-encryption). Evervault Strings can be used across all of our products. To encrypt data using the PHP SDK, simply pass a string or array into the encrypt() method. The encrypted data can be stored in your database as normal and can be used with any of Evervault’s other services.

```php
<?php
$evervault = new Evervault('<APP_ID>', '<API_KEY>');

$encrypted = $evervault->encrypt('Alice');

echo $encrypted;
```

**Parameters**

- `data` `string | array` _(required)_ — The data to encrypt.

### decrypt()

Decrypts the data previously encrypted with the `encrypt()` function or through [Relay](/relay). An API key with the `decrypt` permission must be used to perform this operation.

```php
$decrypted = $evervault->decrypt($encrypted)
```

**Parameters**

- `data` `string | array` _(required)_ — The data to decrypt.

> **PCI Compliance**
>
> Decrypting data with our backend SDKs is not available if you are part of the PCI or HIPAA compliance use cases. Instead you can:
>
> - Use [Relay](/relay) to decrypt data before it reaches third-party services.
> - Use [Functions](/functions) or [Enclaves](/enclaves) to process encrypted data.

### createClientsideDecryptToken()

Client Side Decrypt Tokens are versatile and short-lived tokens that frontend applications can utilise to decrypt data previously encrypted through Evervault. Client Side Decrypt Tokens are restricted to specific payloads.

By default, a Client Side Decrypt Token will live for 5 minutes into the future. The maximum time to live of the token is 10 minutes into the future.

```php
<?php
$evervault = new Evervault('<APP_ID>', '<API_KEY>');
$encrypted = $evervault->encrypt('Alice');
$timeInFiveMinutes = time() + 5*60;

$token = $evervault->createClientSideDecryptToken($encrypted, $timeInFiveMinutes);
```

**Parameters**

- `payload` `string | array` _(required)_ — The payload containing encrypted data that the token will be used to decrypt.
- `expiry` `int` — The time the token will expire in Epoch seconds. Defaults to 5 minutes in the future.

### run()

Lets you invoke an [Evervault Function](/functions) with a given payload.

```php
<?php
$evervault = new Evervault('<APP_ID>', '<API_KEY>');

$encrypted = $evervault->encrypt('Alice');

$result = $evervault->run(
    'hello-function',
    (object) [
        'name' => 'Claude Shannon',
        'ssn' => 'ev:encrypted_string'
    ]
);
```

**Parameters**

- `functionName` `string` _(required)_ — The name of the function to invoke.
- `payload` `object` _(required)_ — The payload to pass to the function.

The `run()` function returns an associative array. This array includes a unique run ID, the status of the execution denoted as success or failure, and, in cases of a successful run, the output generated by the function.

```json
{
  "id": "func_run_09413338da56",
  "status": "success",
  "result": {
    "message": "Hello from a Function! It seems you have 14 letters in your name",
    "name": "ev:RFVC:TTLHY04oVJlBuvPx:A7MeNriTKFES0Djl9uKaPvHCAn9PjSfOHu7tswXFCHF9:jwYKE13o3iQlr6Dn/DRk80XpNOGb:$"
  }
}
```

### createRunToken()

Creates a single use, time bound token (5 minutes) for invoking an [Evervault Function](/functions) with a given payload. If the payload is an empty object, the Run Token will be valid for any payload. Run Tokens can be used to invoke an Evervault Function client-side without providing a sensitive API Key.

```php
<?php
$evervault = new Evervault('<APP_ID>', '<API_KEY>');

$runToken = $evervault->createRunToken(
    'hello-function',
    (object) [
        'name' => 'Claude Shannon',
        'ssn' => 'ev:encrypted_string'
    ]
);

var_dump($runToken);
```

**Parameters**

- `functionName` `string` _(required)_ — The name of the function to invoke.
- `payload` `object` _(required)_ — Payload that the token can be used with.

When you create a Run Token, the SDK will return a JSON object **containing** your token which can then be passed to your client-side application.

```json
{
  "token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsInZlciI6IjAuMCJ9.eyJhcHBVdWlkIjoiYXBwX2RmZGE3MmUwMTZiMCIsImZ1bmN0aW9uTmFtZSI6ImhlbGxvLWNhZ2UtdGFsbC13YWxscy10cmF2ZWwiLCJydW5JZCI6IjRiMjhmMzNlLWU3NjYtNDI2OC1iNmY2LTUyYzZkM2VmMGQzYyIsImV4cCI6MTY2Nzg3Njc2Nn0.gCiFw7UJ8gjZfeXNEaqX4H1Y9HBX9avjioZ4yDU8PTtmGT4QTzVOhnDV46v_yyXLxpO1BgzoBRpYbLciiW1_QXSLmx6cCuJy4vHUZwssHT13vB7AXIl_88Ab5R7w9vpOQIDoCjhPVWJsolwUiiGh_5yE4wGv6WPTIfSv249_hpJLMz3AAffXUckiLPxFporY73KXtTANQH_zniivB91KdBnyGhle7gTs1EXWLqpdMIrqOz9cmoXU31DGd-AgeMzM082s_XtdCFq7FNLLtg6Nx8Mx8Bjl0cKV41R-jbTpHSXxutLX-PSDmWn5wSqDhlQoEWdTLsoS6xp7qhZ2urYyYg"
}
```

Run Tokens can then be used to authenticate Function runs from the client-side.

```javascript
fetch("https://api.evervault.com/functions/[function-name]/runs", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `RunToken [run-token]`,
  },
  body: JSON.stringify({
    payload: {
      ssn: "encrypted_string",
    },
  }),
});
```

> The payload used to invoke your Function must be identical to the payload used
>   to create the Run Token.

### enableOutboundRelay()

Configures your application to proxy HTTP requests using [Relay](/relay) for any requests to Relay destinations sent using the cURL handler provided.

Relay must be enabled for a `CurlHandle` after the destination URL has been set, and before `curl_exec()` is called.

```php
<?php
$evervault = new Evervault('<APP_ID>', '<API_KEY>');

$curlHandler = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://example.com');
$evervault->enableOutboundRelay($curlHandler);

$response = curl_exec($ch);
curl_close($ch);
```

**Parameters**

- `curlHandler` `CurlHandle` _(required)_ — If the destination URL has been added as an Relay destination in the Evervault Dashboard, any requests sent to this destination using the `CurlHandle` provided will be proxied through Relay.

