PHP chroot() Function

PHP chroot() Function

In this tutorial, we will learn how we can effectively restrict processes from accessing files outside the defined root directory in PHP by using the chroot() function.

When it comes to the scope of a server security, one of the most prevalent and efficient method to protect against compromise is isolating the processes to their own directories.

In environments such as web servers, isolating the web server from the rest of the system is a critical feature. This limits the attackers from gaining access to more privilege users such as root or access files outside the web server directory.

In PHP, we have access to the chroot() function that allows us to change the root directory of the current running process to a new target directory.

PHP chroot() Function

The function syntax is as shown below:

chroot(string $directory): bool

The function accepts one main parameter:

  1. directory - this defines the path to the target root directory.

The function will then change the root directory of the current process to the defined directory and sets the current working directory to /.

Upon success, the function will return a boolean true and false if otherwise.

Example Function Usage

The following examples demonstrate how to use the chroot() function to change the current root directory.


Consider the example snippet shown below:

echo getcwd();

The command should return the output:


Example 2

We can also use the chroot() function to run a specific script in a target directory as shown:

$directory = "/path/to/jail";

// execute script
system("/bin/bash -c 'echo Hello World'");

Example 3

The example below also demonstrates how to use PHP chroot to set up PHP-FPM pool with chroot.

chroot = /path/to/chroot

This will set up a PHP-FPM pool with a chroot jail in the specified directory. All requests handled by this pool will be restricted to the files and resources within the jail, providing an additional layer of security for your PHP application.


In this tutorial, we covered the basics of working with the chroot() function in PHP. We also explored some basic examples and common use case of the chroot() function.

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.