Rust

PHP standard library

PHP engine semantics (the value model, juggling and comparison, string, number, JSON, serialize, igbinary, sorting, filter and URL functions) for crates that must behave exactly like PHP.
Rust 37,994 lines (33,127 code)split
PartCodeCommentsBlankTotalFiles
Rust source33,1273,2821,58537,99448
Rust tests1,549291181,69632

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

PHP functions

Browse all 146 →

The PHP engine's own behaviour, reimplemented in Rust so the Utopia crates match PHP byte for byte, each function checked against the real one by recorded cases and fuzzing on every run.

146PHP functions and behaviours
16groups
1,621compat cases
692,570fuzz inputs per run
37,994lines of Rust
45Utopia crates using it
PartCodeCommentsBlankTotalFiles
Rust source33,1273,2821,58537,99448
Rust tests1,549291181,69632

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
php-std = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with PHP standard library, each a complete program you can copy and run.

php-std reproduces PHP built-in functions and value semantics in Rust, byte for byte. When you port PHP code, call the php-std twin of each built-in instead of writing your own approximation, and the Rust code gives the same answer as PHP, edge cases included. Strings are bytes (&[u8]), because PHP strings are bytes. This guide covers the common tasks.

Parse a URL like parse_url

parse_url splits a URL into its parts. A missing part is None, and a URL PHP rejects is None as a whole, where PHP returns false.

Rust
use php_std::url::parse_url;

let url = parse_url(b"https://user:secret@cloud.appwrite.io:8443/v1/users?limit=25#top").ok_or("invalid URL")?;

assert_eq!(url.scheme().as_deref(), Some(&b"https"[..]));
assert_eq!(url.host().as_deref(), Some(&b"cloud.appwrite.io"[..]));
assert_eq!(url.port(), Some(8443));
assert_eq!(url.path().as_deref(), Some(&b"/v1/users"[..]));
assert_eq!(url.query().as_deref(), Some(&b"limit=25"[..]));
assert!(parse_url(b"http://:80").is_none());

Match a regular expression like preg_match

Patterns take PHP's delimiters and modifiers, and run on PCRE2 10.44 with its JIT, the library PHP bundles, called the way PHP calls it. Compile a pattern once with Regex::compiled and read the groups of a match.

Rust
use php_std::pcre::Regex;

let semver = Regex::compiled(b"/^(\\d+)\\.(\\d+)\\.(\\d+)$/").map_err(|_| "invalid pattern")?;

let version = semver.captures(b"1.6.2").ok_or("no match")?;
assert_eq!(version.get(0), Some(&b"1.6.2"[..]));
assert_eq!(version.get(2), Some(&b"6"[..]));
assert!(!semver.is_match(b"1.6"));

Replace text like preg_replace

preg_replace takes the pattern, replacement and subject as a string or an array, like PHP. The result holds the new value and the number of replacements.

Rust
use php_std::pcre::{StrOrArray, Value, preg_replace};

let replaced = preg_replace(
    &StrOrArray::Str(b"/[^a-z0-9]+/i"),
    &StrOrArray::Str(b"-"),
    &StrOrArray::Str(b"Hello, World 2026!"),
    -1,
)?;

assert_eq!(replaced.value.result, Value::Str(b"Hello-World-2026-".to_vec()));
assert_eq!(replaced.value.count, 3);

Encode and decode JSON like json_encode

json::encode and json::decode work on Value, PHP's value model. Floats, escaping and flags follow PHP, and a failure returns the error PHP reports.

Rust
use php_std::json::{self, DEFAULT_DEPTH, Flags};
use php_std::{Array, Value};

let mut user: Array = Array::new();
user.set("name".into(), Value::from("Ana"));
user.set("score".into(), Value::from(4.5));
user.set("site".into(), Value::from("https://appwrite.io"));

let text = json::encode(&Value::Array(user.clone()), Flags::NONE, DEFAULT_DEPTH)?;
assert_eq!(text, r#"{"name":"Ana","score":4.5,"site":"https:\/\/appwrite.io"}"#);

let text = json::encode(&Value::Array(user), Flags::UNESCAPED_SLASHES, DEFAULT_DEPTH)?;
assert_eq!(text, r#"{"name":"Ana","score":4.5,"site":"https://appwrite.io"}"#);

let decoded = json::decode(br#"{"tags":["a","b"]}"#, Some(true), DEFAULT_DEPTH, Flags::NONE)?;
let Value::Array(decoded) = decoded else { panic!("expected an array") };
assert!(matches!(decoded.get_str("tags"), Some(Value::Array(tags)) if tags.len() == 2));

let error = json::decode(b"{bad", None, DEFAULT_DEPTH, Flags::NONE).unwrap_err();
assert_eq!(error.message(), "Syntax error");

Compare values like ==

PHP 8's == compares numeric strings as numbers and other strings as text. Value::loose_eq is ==, Value::strict_eq is ===, and Value::cmp_php is <=>.

Rust
use std::cmp::Ordering;

use php_std::Value;

let hundred: Value = Value::from(100);
let exponent: Value = Value::from("1e2");
let zero: Value = Value::from(0);
let lower: Value = Value::from("abc");
let ten: Value = Value::from("10");
let null: Value = Value::Null;

assert!(hundred.loose_eq(&exponent));
assert!(!hundred.strict_eq(&exponent));
assert!(!zero.loose_eq(&Value::from("a")));
assert!(!lower.loose_eq(&Value::from("ABC")));
assert!(null.loose_eq(&Value::from(false)));
assert_eq!(ten.cmp_php(&Value::from("9")), Ordering::Greater);

Format numbers like number_format

number_format rounds half away from zero and groups the digits by three. sprintf takes PHP's format string and arguments.

Rust
use php_std::format::{Arg, number_format, sprintf};
use php_std::value::Number;

assert_eq!(number_format(Number::Float(1234567.891), 2, b".", b","), b"1,234,567.89");
assert_eq!(number_format(Number::Float(1234.5), 0, b".", b","), b"1,235");
assert_eq!(number_format(Number::Int(1234567), 2, b",", b" "), b"1 234 567,00");

let line = sprintf(b"%-8s|%05.1f|%x", &[Arg::Str(b"cpu"), Arg::Float(3.14159), Arg::Int(255)])?;
assert_eq!(line, b"cpu     |003.1|ff");

Work with multibyte strings

The mb functions count and cut UTF-8 characters, not bytes. strlen is the byte length of the slice.

Rust
use php_std::mb::{mb_strlen, mb_strtolower, mb_substr};

let name = "Zoë Ångström".as_bytes();

assert_eq!(name.len(), 15);
assert_eq!(mb_strlen(name), 12);
assert_eq!(mb_substr(name, 0, Some(3))?, "Zoë".as_bytes());
assert_eq!(mb_strtolower(name), "zoë ångström".as_bytes());

Parse a query string like parse_str

parse_str decodes a query string into an array the way PHP fills $_GET. Dots and spaces in names become _, and name[] builds a nested array.

Rust
use php_std::encoding::parse_str;
use php_std::Value;

let query = parse_str(b"user.name=Ana+Lee&tags[]=a&tags[]=b");

assert_eq!(query.get_str("user_name"), Some(&Value::from("Ana Lee")));
let Some(Value::Array(tags)) = query.get_str("tags") else { panic!("expected an array") };
assert_eq!(tags.get(&1.into()), Some(&Value::from("b")));

Validate input like filter_var

filter_var takes the value, the filter and its flags or options, with PHP's constants. A failed validation returns false, like PHP.

Rust
use php_std::filter::{
    FILTER_FLAG_IPV4, FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_INT, FILTER_VALIDATE_IP, Key, Options, Value, filter_var,
};

let email = filter_var(&Value::Str(b"ana@appwrite.io".to_vec()), FILTER_VALIDATE_EMAIL, &Options::Flags(0))?;
assert_eq!(email.value, Value::Str(b"ana@appwrite.io".to_vec()));

let ip = filter_var(&Value::Str(b"::1".to_vec()), FILTER_VALIDATE_IP, &Options::Flags(FILTER_FLAG_IPV4))?;
assert_eq!(ip.value, Value::Bool(false));

let range = Options::Array(vec![(
    Key::Str(b"options".to_vec()),
    Value::Array(vec![(Key::Str(b"min_range".to_vec()), Value::Int(1)), (Key::Str(b"max_range".to_vec()), Value::Int(100))]),
)]);
let limit = filter_var(&Value::Str(b" 25 ".to_vec()), FILTER_VALIDATE_INT, &range)?;
assert_eq!(limit.value, Value::Int(25));

Reference#

PHP engine semantics in Rust.

Utopia crates must behave exactly like their PHP libraries, and much of that behaviour comes from the PHP engine rather than the library: type juggling, is_numeric, (string) casts, loose comparison, strtolower, mb_*, number_format, json_encode/json_decode, filter_var, parse_url. Each is reimplemented here once, and verified against the real PHP function by bin/compat (library php-std, see tests/compat/php-std). Utopia crates use these functions instead of their own approximations (crates/CONVERSION.md §3).

PHP values are Value (types): byte strings, ordered arrays with integer and string keys, stdClass, and crate-defined objects. The codecs (json, serialize, igbinary), comparisons and sort work on it. Older string-level helpers (value, string, format, filter) take request-model serde_json::Values, decoded the way Utopia\Http\Request decodes bodies (objects are associative arrays, except empty objects, which stay stdClass; Value::from_json is the same mapping).

Modules#

Each module groups one concept of the library. Internal ones hold items the crate re-exports at its root.

csv3 items
CSV parsing: `str_getcsv()` and `fgetcsv()`.
datetime::abbreviationsinternal
Generated by `data/timezonedb.py` from timelib's `timezonemap.h` and `fallbackmap.h`: do not edit.
datetime::formatinternal
`date_format()` of `php_date.c`: the formatter behind `date()`, `gmdate()` and `DateTimeInterface::format()`.
datetime::from_formatinternal
`timelib_parse_from_format` with PHP's default format map: the parser behind `DateTime::createFromFormat()` and `date_parse_from_format()`.
datetime::parseinternal
`timelib_strtotime` (`parse_date.re`): PHP's free-form date/time parser, used by `strtotime()`, `date_parse()`, `new DateTime()`, `DateTime::modify()` and `DateInterval::createFromDateString()`.
datetime::scannerinternal
The matching engine for timelib's re2c scanner: a Thompson NFA built from the rule definitions of `parse_date.re`, simulated to find what the re2c DFA finds: the longest match over all rules, the earliest rule on a tie.
datetime::timelibinternal
timelib's broken-down time and its arithmetic: `timelib_time`, `timelib_rel_time`, `tm2unixtime.c`, `unixtime2tm.c`, `dow.c`, `interval.c` (`timelib_add`).
datetime::tzinternal
PHP's bundled timezone database and timelib's lookups over it (`parse_tz.c`, `parse_posix.c`, the abbreviation search of `parse_date.re`).
datetime::tzindexinternal
Generated by `data/timezonedb.py` from PHP's `timezonedb.h`: do not edit.
datetime15 items
Date and time: date()/DateTime::format, DateTime parsing and timezones, strtotime, microtime.
encoding::html_tablesinternal
HTML entity tables of PHP 8.5.10. Generated by `data/html_entities.py`; do not edit by hand.
encoding20 items
Encodings: URL encoding, `http_build_query`, base64, hex, HTML entities and quoted-printable.
filter::emailinternal
`FILTER_VALIDATE_EMAIL` without its regular expression.
filter::sanitizeinternal
The sanitizing filters of `ext/filter/sanitizing_filters.c` (PHP 8.5), with the parts of `ext/standard` they call: `php_strip_tags_ex()` (`string.c`), `php_escape_html_entities_ex()` (`html.c`, as `FILTER_SANITIZE_FULL_SPECIAL_CHARS` calls it: every HTML 4.01 entity, UTF-8, no double encoding) and `php_addslashes()`.
filter59 items
`filter_var()`: the validation filters (`FILTER_VALIDATE_INT`, `BOOL`, `FLOAT`, `REGEXP`, `URL`, `EMAIL`, `IP`, `MAC`, `DOMAIN`), the sanitizing filters (`FILTER_DEFAULT`/`FILTER_UNSAFE_RAW`, `FILTER_SANITIZE_*`) and `FILTER_CALLBACK`, with their flags and options, ported from `ext/filter` (`logical_filters.c`, `sanitizing_filters.c`, `callback_filter.c`, `filter.c`) of PHP 8.5.
format::arithinternal
PHP's arithmetic operators on numbers (`Zend/zend_operators.c`): integers that overflow become floats, `/` gives an integer only when the division is exact, and dividing by zero throws.
format::powinternal
`pow()` as musl computes it (`src/math/pow.c`, from Arm's optimized routines, MIT licensed): PHP's `**` on floats calls the C library's `pow`, and the dev image is Alpine. This is not correctly rounded (the worst case is 0.54 ULP), so a correctly rounded or platform `pow` differs from PHP's in the last digit for some inputs. The fused multiply-add paths are the ones musl takes where the target has FMA (`__FP_FAST_FMA`, aarch64).
format19 items
Number formatting and casts: `sprintf`, `number_format`, `round`/`ceil`, `intval`/`floatval` and the `(int)` / `(float)` casts, `fmod`, `max`/`min` of numbers.
glob::classesinternal
The code points musl puts in each `[:class:]` of a glob in a UTF-8 locale, as `(first, last)` ranges.
glob1 items
Shell glob matching: PHP's `fnmatch()`.
igbinary4 items
`igbinary_serialize` and `igbinary_unserialize`, byte-identical to the igbinary extension (3.2, format version 2, `igbinary.compact_strings=On`) of the PHP image. Appwrite's cache and queue payloads use it.
json10 items
`json_encode`, `json_decode`, `json_validate`, `json_last_error` and `json_last_error_msg`, as PHP 8.5's `ext/json` implements them.
mb::unicodeinternal
Unicode case data of PHP's mbstring, generated from php-src `ext/mbstring/unicode_data.h` (tag `php-8.5.10`) by `data/unicode.py`. Do not edit by hand.
mb::widthinternal
The code points mbstring counts two columns wide (`mb_strwidth`, `mb_strimwidth`): its East Asian Width table, as `(first, last)` ranges.
mb9 items
Multibyte (mbstring) functions on UTF-8.
net4 items
Network helpers: `inet_pton`/`inet_ntop`.
number3 items
How PHP prints floats.
path5 items
Path functions.
pcre::compiledinternal
A PHP regex compiled once and matched many times: `preg_match()` without the per-call cache lookup, for libraries that run fixed patterns on a hot path (`utopia-user-agent` runs its tables on every request).
pcre::engineinternal
PCRE2 as `ext/pcre` holds it: compiled patterns shared by every thread, and per thread the match context (`pcre.backtrack_limit`, `pcre.recursion_limit` and the 32 KiB–192 KiB JIT stack) and the preallocated match data `php_pcre_init_pcre2()` creates.
pcre::ffiinternal
The PCRE2 10.44 API (`pcre2.h`, 8-bit library) that `ext/pcre` uses, linked from the sources `build.rs` compiles.
pcre26 items
PHP's PCRE functions: `preg_match`, `preg_match_all`, `preg_replace`, `preg_split` and `preg_quote`, on PCRE2 10.44 with its JIT, the library and version PHP 8.5 bundles.
random1 items
Random numbers: PHP's Mersenne Twister, the engine behind `mt_rand()`, `rand()`, `array_rand()` and `shuffle()`.
serialize7 items
`serialize`, `unserialize` and `var_export`, in PHP 8.5's formats.
sort12 items
PHP's array sorting and set functions: `sort`, `ksort`, `array_unique`, `array_diff`, `array_intersect`, `in_array` and `array_search`, with the `SORT_*` flags.
string::tablesinternal
Constant tables of PHP's ext/hash for `hash()` (from php-src 8.5: `php_hash_tiger_tables.h`, `php_hash_snefru_tables.h` and `hash_haval.c`, PHP License 3.01).
string40 items
Byte-string functions of `ext/standard/string.c` and `ext/ctype`, plus `crypt()`, `password_hash()` / `password_verify()` and `hash()`.
system3 items
Process and host functions.
types::arrayinternal
`Array`: a PHP array (an ordered map with integer and string keys).
types3 items
The PHP value model: `Value`, `Str`, `Array`, `ArrayKey`.
types::strinternal
`Str`: a PHP string, which is a byte string.
types::valueinternal
`Value`: a PHP value, and the engine's type juggling and comparison on it.
url::rfc39861 items
`Uri\Rfc3986\Uri` from the PHP 8.5 URI extension.
url4 items
`parse_url` and the PHP 8.5 URI extension (`Uri\Rfc3986\Uri`).
value16 items
PHP value semantics (type juggling) on top of `serde_json::Value`.
yaml1 items
`yaml_parse()` (ext-yaml 2.3 over libyaml 0.2.5) with the default ini settings: timestamps, `!!binary` and `!php/object` stay strings.

API#

What php_std exports at its root.