# PHP FFI (Foreign Function Interface)

The Foreign Function Interface (FFI) extension allows you to call functions and access data structures from C libraries directly in your PHP code. This is a powerful feature that allows you to use existing C libraries without having to write a full-blown PHP extension.

FFI was introduced in PHP 7.4.

## Enabling FFI

The FFI extension is usually not enabled by default. You need to enable it in your `php.ini` file:

```ini
ffi.enable=1
```

For security reasons, `ffi.enable` can only be set in `php.ini`. However, you can also enable FFI on a per-script basis for CLI scripts.

## Basic Usage

To use FFI, you first need to create an FFI object. You can do this by defining the C functions and data structures you want to use in a string.

```php
<?php
// Create an FFI object and define the C function signature
$ffi = FFI::cdef(
    "int printf(const char *format, ...);", // C function signature
    "libc.so.6" // The C library to load
);

// Call the C function
$ffi->printf("Hello, %s!\n", "world");
?>
```

In this example, we're calling the `printf` function from the standard C library (`libc`).

## Working with C Data

FFI also allows you to work with C data structures.

```php
<?php
$ffi = FFI::cdef(
    "typedef struct { int x; int y; } point;",
    "libc.so.6"
);

// Create a new C data structure
$point = $ffi->new("point");

// Access the fields of the structure
$point->x = 10;
$point->y = 20;

var_dump($point->x); // 10
?>
```

## Use Cases

-   **Performance:** For computationally intensive tasks, you can write a C library and call it from PHP using FFI. This can be significantly faster than writing the same logic in pure PHP.
-   **Reusing Existing Libraries:** There are many high-quality, battle-tested C libraries available. FFI allows you to leverage these libraries in your PHP applications.
-   **Interacting with the OS:** FFI can be used to call low-level OS APIs that are not exposed by PHP's standard library.

## Security Considerations

FFI is a powerful but potentially dangerous feature. It allows you to call any function in any C library, which can lead to security vulnerabilities if not used carefully. For this reason, it's recommended to only use FFI in trusted environments and to carefully validate all input that is passed to FFI functions. In a web server environment, it's often disabled for this reason.
