Getting started
Installation
CmdStanPHP is a Composer package that runs CmdStan, Stan’s command-line interface. Installing it takes three steps: the Composer package, a C++ toolchain, and a CmdStan release.
Requirements
Required:
- PHP 8.2, 8.3, 8.4, or 8.5
- The JSON extension
- PHP’s
proc_open()function - CmdStan 2.37 or later
- make and a C++ compiler that CmdStan supports
Optional:
- The FFI extension, for in-process log densities, gradients, and transforms, and for calling a model’s Stan functions from PHP
- The phit extension, for moment matching in
loo()and forStanData::fromFormula() - phibble, for model data from a
Phibble\DataFrameand for draws and summaries returned as data frames - vl-convert, for figures saved as SVG or PNG
composer.json allows PHP >=8.2 <8.6. CI runs the unit tests on PHP 8.2, 8.3, 8.4, and 8.5, and the integration tests on PHP 8.4 with CmdStan 2.37.0 and 2.40.0.
proc_open() must be enabled, because every compilation and every run starts a CmdStan process. Hosts that list it in disable_functions cannot run models.
Supported platforms
CI runs every test on Linux (Ubuntu). The integration suite also passes on macOS on Apple silicon. Native Windows has not been tested. The code chooses Windows file suffixes and compiler names, but no Windows build or run has been checked. On Windows, run PHP inside WSL, which uses the tested Linux path.
Install the package
composer require phpstats/cmdstanphpThe package has no Composer dependencies of its own.
Install a C++ toolchain
CmdStan compiles each Stan program to a C++ executable, so compiling needs make and a C++ compiler. The CmdStan installation guide lists the supported compilers.
- macOS: install the Xcode command-line tools with
xcode-select --install. This providesmakeandclang++. - Debian and Ubuntu:
sudo apt-get install build-essentialprovidesmakeandg++.
Install CmdStan
If CmdStan 2.37 or later is already installed, skip to selecting CmdStan.
install_cmdstan() downloads an official release from GitHub, builds it, and selects it:
require 'vendor/autoload.php';
$path = CmdStan\install_cmdstan('2.40.0', cores: 2, timeout: 1800);
echo $path, "\n";The release goes into ~/.cmdstan/cmdstan-2.40.0, or into the directory given as dir. Without a version, the installer takes the latest release. Versions before 2.37 are rejected. Installing needs curl, tar, make, the C++ compiler, internet access, and enough memory for compilation. The build takes several minutes. cores sets the number of parallel make jobs, and timeout is in seconds.
The installer checks the archive’s entry paths and links before extracting, extracts into a private staging directory, and builds at the final location. It refuses to replace an installed version unless overwrite: true is passed. With overwrite: true the old installation is kept until the new build succeeds and is restored if the build fails.
Other ways to install:
CmdStan\install_cmdstan(releaseFile: '/downloads/cmdstan-2.40.0.tar.gz');
CmdStan\install_cmdstan(releaseUrl: 'https://example.com/cmdstan-2.40.0.tar.gz');
CmdStan\install_cmdstan('2.40.0', cppOptions: ['STAN_THREADS' => true]);releaseFileis a local.tar.gzandreleaseUrlan HTTPS.tar.gzURL. The version is read from the archive’s top-levelcmdstan-*directory.cppOptionsare written to CmdStan’smake/localbefore the build.copyMakeLocal: truefirst copies themake/localof the CmdStan in use into the new installation. The default,null, asks in an interactive terminal and otherwise does not copy.
cmdstan_make_local() reads, appends to, or replaces the selected installation’s make/local, and rebuild_cmdstan(cores: 2) runs clean-all and build on it.
Select CmdStan
Without an explicit path, CmdStanPHP uses the directory in the CMDSTAN environment variable. If CMDSTAN is not set, it uses the highest supported version under ~/.cmdstan/cmdstan-*. install_cmdstan() selects the release it installed for the rest of the PHP process.
To choose an installation explicitly:
CmdStan\set_cmdstan_path('/opt/cmdstan/cmdstan-2.40.0');The path must contain CmdStan’s makefile and the stanc compiler. set_cmdstan_path() refuses a version before 2.37. A web server or queue worker that runs under its own account does not see your home directory, so set CMDSTAN or call set_cmdstan_path() with an absolute path there.
Check the installation
require 'vendor/autoload.php';
echo CmdStan\cmdstan_path(), "\n";
echo CmdStan\cmdstan_version(), "\n";
print_r(CmdStan\check_cmdstan_toolchain());On macOS with CmdStan 2.40.0 this prints:
/Users/you/.cmdstan/cmdstan-2.40.0
2.40.0
Array
(
[make] => Array
(
[path] => /usr/bin/make
[version] => GNU Make 3.81
)
[cxx] => Array
(
[name] => clang++
[path] => /usr/bin/clang++
[version] => Apple clang version 21.0.0 (clang-2100.3.34.2)
)
[stanc] => Array
(
[path] => /Users/you/.cmdstan/cmdstan-2.40.0/bin/stanc
[version] => stanc3 42d3cdf (Unix)
)
)
cmdstan_path() throws when no CmdStan installation is found. check_cmdstan_toolchain() throws when make or the C++ compiler is missing. It does not install missing tools, and a successful check does not prove that a compilation will succeed.
Compile a first model
Getting started compiles and samples the Bernoulli example. A model is compiled once, and later runs reuse its executable until the program or its build settings change.
Compiling writes two hidden files beside the executable: a build record, .<exe>.cmdstanphp.json, and a lock file, .<exe>.cmdstanphp.lock. If your .gitignore ignores model executables, ignore these too:
.*.cmdstanphp.json
.*.cmdstanphp.lock
Optional extensions
FFI
In-process model methods (logProb(), gradLogProb(), hessian(), constrainVariables(), unconstrainVariables()) and exposeFunctions() load a compiled model library with PHP’s FFI extension. FFI is enabled for the CLI by default (ffi.enable=preload). PHP-FPM and other web SAPIs need ffi.enable=true in php.ini, or a preloaded library. Without FFI these methods throw a RuntimeException, and everything else works.
phit
loo(momentMatch: true) needs the posterior-draw kernels Phit\draws_moments(), Phit\draws_covariance_map(), and Phit\draws_affine(). StanData::fromFormula() needs Phit\model_matrix(). Every phit release from 0.1.0 has these functions. Install phit with PIE as phit’s documentation describes:
pie install phpstats/phitCmdStanPHP checks for these functions by name. Without them, the two features throw a RuntimeException that names the missing functions.
phibble
composer require phpstats/phibbleWith phibble installed, a Phibble\DataFrame can be passed as model data, and drawsTable() and summaryTable() return data frames. phibble requires PHP 8.3 or later. Without phibble, drawsColumns() and summaryColumns() return the same data as plain column arrays.
vl-convert
Figure::svg() and Figure::png() run the vl-convert binary. Download it for your platform, then put vl-convert on PATH or set VL_CONVERT to its path. ASCII, Vega-Lite, and HTML figures need nothing extra.