October 15, 2026

Everything Is an Array: Taking a PHP App to Rust

Reading the PHP is the easy part. The hard part is everything PHP does for you without saying so: values that quietly become strings, missing fields that become null, errors printed into the JSON, and a database connection in a character set nobody chose. Here's how we found those rules in a real PHP API, moved it route by route behind nginx to Rust, and proved every response matches byte for byte.

Everything Is an Array: Taking a PHP App to Rust

PHP runs a huge share of the web, and modern PHP is a good language. PHP 8 brought a JIT compiler, union types, enums and readonly properties. If your PHP app works and your team likes it, there's no rule that says you have to leave.

But some teams have good reasons to move part of it. A few endpoints get most of the traffic and need to be faster. Background workers keep running out of memory. The codebase has grown to the point where nobody trusts a change until it's been in production for a week. Rust is a strong choice for those parts. It's fast, it uses little memory, and its type system catches mistakes before the code runs.

Reading the PHP turned out to be the easy part. What's hard is everything PHP does without anyone writing it down. Values quietly turn into strings. A missing field becomes null and a warning in the response. The database connection uses a character set nobody chose. Your API clients depend on all of it, whether you meant them to or not. Rust makes you write each of those rules down, so most of a migration is finding them.

The example: every snippet in this post comes from a real API you can run: php_rest_api_without_framework, a students API in plain PHP with PDO and MySQL, and our Rust rewrite of it with axum and sqlx. It's five scripts and 341 lines: list, get one, add, update and delete. Both versions, the recorded traffic and the nginx setup are at cobuild-tech/migratex-examples. Where Laravel or Symfony changes the picture, we say so.

Before You Start

Before you start: list every route, model, session, queue, cron job and Composer package. Write down the loose rules PHP applies for you, such as values turned into strings, missing fields that become null, and the connection's character set. Then record real requests and responses to compare against later

Should you move at all?

Be specific about why. "PHP is slow" isn't a good reason anymore. PHP 8 is fast, and most web pages spend their time waiting on the database anyway. Good reasons look more like: this one endpoint handles most of our traffic and costs us a lot of servers. Or our queue workers need to run for days without leaking memory. Or we want the compiler to catch the bugs our tests keep missing.

Then move only those parts. Rewriting a whole PHP app in one go is how projects stall for a year. With a proxy in front, you can move a single route and leave everything else exactly where it is.

Make a list of everything that runs

  • Routes, with their methods, and which ones get the most traffic. Your access logs will tell you.
  • The framework, if there is one. Laravel and Symfony do a lot on your behalf: middleware, validation, model events, cookie encryption. Each of these has to be found and rebuilt.
  • Models and queries, including ORM features like casts, accessors and observers that change data on the way in or out.
  • Sessions and auth. Where are sessions stored, and in what format?
  • Queues and cron jobs. These are often the best place to start, because no user waits on them directly.
  • Composer packages, and what each one would become in Rust.
  • php.ini settings that change behaviour, like display_errors, the timezone, and memory and time limits.

Our example is small: five scripts in api/, one model, one database class, no framework, no sessions, no queues. Small doesn't mean simple, though. Every rule below came out of those 341 lines.

Write down what PHP does for you

Here's the heart of put.php, which updates a student:

$data = json_decode(file_get_contents("php://input"));

$student->id = isset($data->id) ? $data->id : NULL;
$student->name = $data->name;
$student->address = $data->address;
$student->age = $data->age;

if(! is_null($student->id)) {
    if($student->putData()) {
        echo json_encode(array('message' => 'Student updated'));
    } else {
        echo json_encode(array('message' => 'Student Not updated, try again!'));
    }
} else {
    echo json_encode(array('message' => "Error: Student ID is missing!"));
}

It's short and it works. It also depends on a lot of rules that aren't written anywhere in it. We found every one of these by running the original:

What PHP doesWhat we sawWhat it means for Rust
Turns every bound value into a string"age": true is stored as 1, 19.5 as 20, and ["a"] as the name ArrayDecide which types you accept, and convert the rest PHP's way while you need to match
Lets the database compare loosely{"id": "16abc"} finds, updates or deletes student 16Every id check is a decision: copy it, or reject it
Treats a missing property as nullA missing age prints a notice, then fails on NOT NULL with a stack traceUse Option, and say what happens when it's None
Has its own idea of "set"isset is false for "id": null, but true for 0, "" and falseWrite the rule out once, in one function
Returns every column as a string"id":"15", "age":"23" (PHP 7.3; PHP 8.1 changed this)Match the version running in production, not the newest one
Escapes JSON its own way\/ for /, \u00e9 for éYour JSON encoder has to agree, byte for byte
Prints errors into the responsedisplay_errors = On: HTML notices inside an application/json body, with HTTP 200Errors are part of the contract until you change them on purpose
Connects with the server's default charsetlatin1 to utf8 columns: é is stored as éConnect the same way, or the two apps disagree about the data

That PHP version note matters. In PHP 8.1, PDO started returning integers and floats as native types with emulated prepares, so the same code sends "id":15 instead of "id":"15". The dump in the repository says PHP 7.3.19 with MariaDB 10.4, so that's what we ran: PHP 7.3 under Apache with XAMPP's settings, in Docker, with the PHP code mounted unchanged.

Record real traffic before you change anything

Save a sample of real requests and the responses PHP sent back, for every route you plan to move. Mask the personal data, but keep the strange ones. These golden pairs are your spec. The Rust version is correct when it gives the same response to the same request.

Our example has no production traffic, so we wrote it: 28 scripted sessions, 79 requests, covering every endpoint, every method and every odd input we could think of. One session is just a text file:

POST /api/post.php {"name":"Lee","address":"Ooty"}
POST /api/post.php
GET /api/get.php

A script resets the database, replays each session against PHP, and saves the status, the headers clients see, the body, and the table afterwards, with text in hex so the stored bytes are compared too. Here's what PHP sent back for that first request, a student with no age:

HTTP/1.1 200 OK
Content-Type: application/json

<br />
<b>Notice</b>:  Undefined property: stdClass::$age in <b>/var/www/html/api/post.php</b> on line <b>20</b><br />
<br />
<b>Fatal error</b>:  Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'age' cannot be null in /var/www/html/models/Student.php:53
Stack trace:
#0 /var/www/html/models/Student.php(53): PDOStatement-&gt;execute()
...

HTML, a stack trace and status 200, as JSON. If a client somewhere checks for Fatal error in the body, that's its error handling. That's why the recordings come before any decisions.

Running PHP and Rust Together

Running PHP and Rust together: settle the shared database first, including its character set. nginx sends each script's URL to either the Rust service or PHP, and both use the same database. Routes move to Rust one at a time until PHP has none left

As with our other migrations, we move one piece at a time while the rest keeps running. Martin Fowler calls this the strangler fig pattern. For a web app the natural piece is a route, and the tool is the proxy you probably already have.

One route, one owner

Put the Rust service, written here with axum, next to PHP, and let nginx choose. In this API the routes are file names, so Rust serves the same paths:

upstream php  { server php:80; }
upstream rust { server rust:8080; }

server {
    location = /api/get.php     { proxy_pass http://rust; }   # moved
    location = /api/get_one.php { proxy_pass http://rust; }   # moved
    location = /api/post.php    { proxy_pass http://php; }
    location = /api/put.php     { proxy_pass http://php; }
    location = /api/delete.php  { proxy_pass http://php; }
}

Each route belongs to exactly one side. If you need to switch back, you change one line and reload nginx. Move a route with all of its methods together. Here each script answers every method itself, with a 200 and Error: incorrect Method! for the wrong one, so the Rust routes accept every method too and answer the same way.

Share the database, carefully

Both sides use the same database while the move is happening. That's fine, but check how PHP talks to it, not only what it stores. Our example connects like this:

new PDO("mysql:host=$this->host;dbname=$this->db", $this->user, $this->pwd);

There's no charset in that string, so the connection uses the server's default, latin1. The columns are utf8. So MariaDB reads every byte PHP sends as a separate latin1 character and stores é (two bytes) as é (two characters, four bytes). Reading it back reverses the conversion, so PHP never noticed. A Rust service that connects as utf8mb4, as sqlx does by default, would store é correctly, and then the two apps would show different names for the same row. So the Rust side connects the same way:

let options = MySqlConnectOptions::from_str(url)?
    .charset("latin1")
    .collation("latin1_swedish_ci")
    // sqlx adds these to every session by default. PHP doesn't.
    .pipes_as_concat(false)
    .no_engine_substitution(false)
    .timezone(None);

Fixing the stored text is a data migration, and it comes after PHP is gone. With an ORM, look for the same kind of thing in observers that write audit rows, accessors that reformat a field, or a cache that PHP clears after every save. If the Rust side skips them, the PHP side reads data it doesn't expect.

Sessions are the tricky part

Our example has no logins, which is its own finding: with no authentication and Access-Control-Allow-Origin: *, any web page can call all five endpoints, writes included. Most apps do have sessions, though. By default, PHP keeps them in files on the server, in its own serialisation format, and Laravel also encrypts its cookies. A Rust service can't read either easily. You can move sessions to Redis and store them as JSON, with a small custom session handler on the PHP side. Or you can switch logins to signed tokens that both sides can check. Do this first, as its own change, before any route moves. Then a login problem never gets mixed up with a migration problem.

From Arrays to Types

From arrays to types: in compat mode, PHP's rules for reading properties and converting values are written down as functions. In the fixed mode, ids and fields get real types and anything else is rejected with a 400 or 422

In PHP, data is whatever json_decode gives you, and you reach into it with $data->name. In Rust you normally describe the shape once with serde, and the compiler checks every use. But a strict struct can't reproduce PHP while both are live. PHP accepted true, 19.5, ["a"] and {} as a name, and clients may send any of them. So the port has two modes, as our COBOL port did:

  • Compat mode (STUDENTS_COMPAT=1) answers exactly as PHP did, notices and stack traces included. It runs while both sides serve traffic, and it's what the golden tests check.
  • The default mode fixes the bugs. Each fix has a comment saying what PHP did, and its own test.

Write PHP's rules down

Compat mode keeps the body as a serde_json::Value and goes through it the way PHP would. Reading a property is one function, notice included:

/// `$data->name` in an endpoint script, on `line`. Reading a missing
/// property gives `null` and a notice.
pub fn prop<'a>(&mut self, data: &'a Option<Value>, name: &str, line: u32) -> Option<&'a Value> {
    let file = self.script_path();
    match data {
        Some(Value::Object(map)) => {
            let value = map.get(name);
            if value.is_none() {
                self.notice(&format!("Undefined property: stdClass::${name}"), &file, line);
            }
            value.filter(|v| !v.is_null())
        }
        _ => {
            self.notice(&format!("Trying to get property '{name}' of non-object"), &file, line);
            None
        }
    }
}

Binding a value is another. PDO's emulated prepares send every value as a quoted string, so this is PHP's string conversion:

Some(Value::Bool(true)) => Some("1".into()),
Some(Value::Bool(false)) => Some(String::new()),
Some(Value::Number(n)) => Some(number_to_string(n)),   // 1e20 is "1.0E+20"
Some(Value::String(s)) => Some(s.clone()),
Some(Value::Array(_)) => {
    self.notice("Array to string conversion", MODEL, line);
    Some("Array".into())
}
Some(Value::Object(_)) => {
    // "Object of class stdClass could not be converted to string"
    return Err(Halt);
}

The SQL is the model's SQL, unchanged, run with sqlx. Values are bound as strings, as PDO did, so MariaDB makes the same conversions: "19.5" is stored as 20, and "16abc" matches id 16. We used sqlx::query rather than the query! macros, so the crate builds without a database. A larger project would want the macros, which check every query against the real schema when the code compiles.

Then give it real types

The default mode is where Rust's types come in. Here's what counts as an id now:

/// An id is a positive whole number, or a string of digits, which is what
/// clients of the PHP version sent. PHP took anything: `"16abc"` meant 16 and
/// `[15]` meant `"Array"`.
fn id(data: &Map<String, Value>) -> Result<u32, Reply> {
    match data.get("id") {
        None | Some(Value::Null) => Err(missing()),
        Some(Value::Number(n)) => n.as_u64().and_then(|n| u32::try_from(n).ok())
            .filter(|&n| n > 0).ok_or_else(invalid),
        Some(Value::String(s)) if !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) => {
            s.parse().ok().filter(|&n| n > 0).ok_or_else(invalid)
        }
        Some(_) => Err(invalid()),
    }
}

Accepting "16" as well as 16 is the choice you'll make again and again. PHP accepted both without complaint. Rust's default would reject the string. If clients really send strings, and the golden pairs will tell you, accept them on purpose, the way this does. Either way, it's now a written decision rather than an accident.

Frameworks

With Laravel or Symfony, much of the logic sits in configuration rather than code. That includes validation rules, middleware, model casts, events and listeners. List them for each route you move, and turn each one into ordinary Rust: an extractor, a layer from tower, or a function call. Error responses need special care. Laravel returns validation errors in its own JSON shape with a 422 status, and front ends often read that shape directly.

Matching the Edge Cases

Matching the edge cases: PHP's JSON shape, such as numbers sent as strings, an object instead of an empty list, and its own escaping; HTTP 200 for every reply, with HTML notices and stack traces in the body; and request details like an id read from a GET body

Clients don't see your code. They see your JSON. Most of the differences we found were in the response, not the logic.

  • Always 200. A wrong method, a missing id, an unknown id and a fatal error all come back as HTTP 200. Clients have learned to read the message instead.
  • An empty list isn't a list. With no rows, get.php sends {"message":"No records found!"} instead of [], so every client handles two shapes.
  • Numbers as strings. PDO on PHP 7.3 returns every column as a string, so PHP sent "age":"23". Compat mode formats the integers as strings too.
  • PHP's own JSON. json_encode writes \/ for / and \u00e9 for é, and gives nothing at all for invalid UTF-8. Any JSON parser reads both forms the same, but byte-for-byte comparison won't, so compat mode encodes exactly as PHP does.
  • Floats print with 14 digits. "age": 1e20 reaches the database as 1.0E+20, which is why it fails with "Out of range value" rather than something else. The port has PHP's float formatting, with a test for it.
  • Errors carry file paths and line numbers. Notices and stack traces name /var/www/html/api/post.php and the line. Compat mode prints the same paths and lines, and HTML-escapes the message as html_errors does.
  • A GET with a body. get_one.php reads the id from a JSON body on a GET request. Some clients and proxies drop GET bodies, but moving the id to the query string changes the API, so it isn't a port decision.
  • Headers too. put.php and delete.php send Access-Control-Allow-Methods: POST, copied from post.php. A browser's preflight reads that.

The biggest bug wasn't in a response at all. Database.php catches the exception as $exp and then reads $e. So when the database is down, the error handler itself fails. Clients get a notice about an undefined variable and a fatal error, with status 200. We recorded that too, by stopping the database, and compat mode reproduces it.

In the default mode all of these are fixed: proper status codes (400, 404, 405 with Allow, 422, 503), [] for an empty list, numbers as numbers, a 404 for updating or deleting an id that doesn't exist, a 201 with the new id from post.php, and the right Allow-Methods on each route. Those change what clients see, so they belong in an announced release after the move. During the move, run compat mode.

Testing the Migration

Testing the migration: the same recorded sessions go to the PHP app and the Rust service, each with the database reset first, and the status, headers, body and stored rows are compared byte for byte. Tests for each fix cover the default mode, and read-only traffic can be mirrored to Rust in production

Many PHP apps have patchy tests, but every one of them has logs and real traffic. That's where we start.

  • Replay the golden pairs against the Rust version, with the database reset to the same dump before each session. Our test replays all 28 sessions against the router in compat mode and compares the status, the headers, the body bytes and the stored rows. A failure prints the request and both bodies.
  • Check the check. We removed the latin1 setting from the Rust connection and ran the tests again. They failed on the stored bytes, so they guard that rule.
  • Replay from outside too. The capture script takes a base URL, so we pointed it at the running Rust service, and then at nginx with two routes on Rust and three on PHP. Both recorded files identical to PHP's. Recording PHP twice also gave identical files, so the recordings are deterministic.
  • Unit tests for the fixed mode, one per fix, with a comment saying what PHP did. And one more for a constraint: a name written by either mode reads back the same in both, so the shared database stays consistent.
  • Mirroring in production. nginx's mirror directive can send a copy of real traffic to the Rust service, which throws its responses away, while you compare them offline. Do this only for read-only routes, or against a separate database. Mirroring post.php to a service that shares the real database adds every student twice.

Finishing the Migration

Finishing the migration: each route has served real traffic from Rust without differences, the nginx rules for PHP are removed, unused Composer packages and PHP code are deleted, PHP-FPM is shut down, and the rollback path is kept until a quiet period has passed

A route is done when Rust has served it in production through a busy period, such as a month end or a sale, with no differences in the replayed traffic and no client complaints. Then:

  1. Delete the PHP code for that route, and any models, helpers and Composer packages nothing else uses. Unused PHP left lying around is a trap for the next person who searches the codebase.
  2. Keep the nginx rule ready to switch back for a few weeks after each move.
  3. Move the cron jobs and queue workers. They're often easier than the routes, because no user is waiting on them.
  4. When the last route has moved, retire sessions in the old format, shut down PHP, and remove it from your images and servers. Then switch to the default mode, fix the stored text, and connect as utf8mb4, each as its own announced change.
  5. Write down the decisions you made along the way: which loose rules you copied, which ones you fixed, and why. Our example's README does this. That record replaces the knowledge that used to live in isset and ==.

One route at a time, and nobody outside the team ever notices the switch.

About MigrateX

MigrateX

MigrateX is our platform and service for moving software, data and infrastructure from one technology to another. It combines automation with experienced engineers. The automation does the repetitive work quickly, and the engineers make the tricky decisions.

This guide is how we approach PHP to Rust projects with MigrateX. Here's what that looks like:

  1. Assessment. We list every route, model, session, queue and cron job, and every loose rule PHP applies for you: values turned into strings, missing fields, errors in the response, and how the database connection is set up. You see where the work is before anyone agrees on a timeline.
  2. Plan. We work with your team to decide which routes move first, and which PHP behaviour to copy exactly and which to fix on purpose.
  3. Migration, step by step. Automation handles the repetitive parts, like writing down PHP's conversions and porting queries to checked SQL. Our engineers handle the parts that need thought, like sessions, character sets and framework behaviour.
  4. Proof that it works. We record real traffic and replay it against both versions. A route only counts as moved when the responses match.
  5. Handover and clean-up. We remove the old code and PHP, keep a way to switch back until things are quiet, and leave your team with a Rust codebase they understand and own.

What you get along the way:

  • No big launch day. Your app keeps running and getting new features while routes move one at a time.
  • Less risk. Replayed traffic and a one-line way to switch back mean clients won't notice the move.
  • A team that's ready. We work alongside your developers the whole time, so they're comfortable with Rust well before the last .php file is gone.
  • More than one kind of move. We use the same approach for COBOL, for front ends like Angular, Ember and jQuery, and for data and infrastructure moves too.

To see the code behind this guide, visit github.com/cobuild-tech/migratex-examples. Got a PHP app with a few routes that need to be much faster, or a codebase nobody trusts anymore? We'd love to hear about it. Tell us a little about it through Contact Us, and we'll start with a free chat about where the work is likely to be.

References

Migration strategy

  1. M. Fowler. StranglerFigApplication. martinfowler.com, 29 June 2004. https://martinfowler.com/bliki/StranglerFigApplication.html
  2. M. Feathers. Working Effectively with Legacy Code. Prentice Hall, 2004.

PHP and MySQL

  1. PHP Manual. Type Juggling. https://www.php.net/manual/en/language.types.type-juggling.php
  2. PHP Manual. isset. https://www.php.net/manual/en/function.isset.php
  3. PHP Manual. json_encode. https://www.php.net/manual/en/function.json-encode.php
  4. PHP Manual. PDO_MYSQL DSN. https://www.php.net/manual/en/ref.pdo-mysql.connection.php
  5. PHP. PHP 8.1 UPGRADING notes (PDO MySQL integers and floats with emulated prepares). https://github.com/php/php-src/blob/PHP-8.1/UPGRADING
  6. MariaDB. Setting Character Sets and Collations. https://mariadb.com/kb/en/setting-character-sets-and-collations/

The example

  1. Hanoak. php_rest_api_without_framework: a REST API in plain PHP with CRUD operations. MIT. https://github.com/hanoak/php_rest_api_without_framework
  2. CobuildX AI. migratex-examples: the students API and its Rust rewrite, with golden sessions recorded from PHP 7.3 and an nginx route switch. https://github.com/cobuild-tech/migratex-examples/tree/main/php-rust