PHP chroot() 目录函数



PHP 的 chroot() 目录函数是一个很有用的函数,用于将当前进程的根目录更改为给定的目录。因此,它对于保持程序在运行时的组织性和安全性非常有帮助。chroot 代表“更改根目录”。

chroot() 函数允许您指定要工作的文件夹。然后,PHP 程序可以访问该文件夹内唯一可用的文件和资源。

使用 chroot() 函数时需要注意的重要事项:

  • 这对于安全性非常有帮助,因为它可以阻止程序弄乱它不应该弄乱的东西。
  • 因此,您可以使用“chroot()”将 PHP 脚本保持在安全的环境中,并保护它们免受计算机上其他文件和文件夹的侵害。
  • PHP 需要使用 --enable-chroot-func 进行配置,在我的机器上只有 root 用户可以使用它。

语法

以下是 PHP chroot() 目录函数的语法:

bool chroot ( string $directory )

参数

使用 chroot() 函数所需的参数如下:

序号 参数及说明
1

directory(必需)

新的根目录

返回值

成功返回 TRUE,失败返回 FALSE。

PHP 版本

chroot() 函数首次出现在 PHP 4.0.5 的核心版本中,并在 PHP 5、PHP 7 和 PHP 8 中继续轻松运行。

示例

在这个例子中,我们将使用 PHP 的 chroot() 目录函数来更改具有给定路径的根目录。

此方法将路径作为输入,该路径链接到新的根目录。此函数的目的是将给定路径设置为根目录。如果此操作成功,则结果将保存在变量中。

<?php
      // Changing root directory 
   $success = chroot("path/to/new/root/directory/"); 
   if($success == true) 
   { 
      echo("Root directory changed successfully."); 
   } 
   else
   { 
      echo("Failed to change root directory."); 
   } 
?> 

输出

这将产生以下结果:

  • 如果 chroot() 函数调用成功
  • Root directory changed successfully.
    
  • 如果 chroot() 函数调用失败
  • Failed to change root directory.
    

    示例

    现在,我们将使用 chroot() 函数将根目录更改为您的特定目录,作为您文件的根目录。因此,基本上我们将访问权限限制在特定文件上,从而提高安全性并设置 PHP 脚本可以执行的私有环境。

    <?php
       // mention the directory to act as the new root
       $newRoot = "/Users/Abc/Desktop/PHP"; // Path to your directory
    
       // try to change the root directory
       if (chroot($newRoot)) {
    
          // Perform operations within the restricted environment
          echo "Accessing files within the restricted directory.<br>";
    
          $contents = file_get_contents("/file/inside/restricted/directory/file.txt");
          echo "Contents of file: $contents";
       } else {
          // Failed to change root directory
          echo "Failed to change root directory.<br>";
       }
    ?> 
    

    输出

    这将产生以下结果:

  • 如果我们已成功更改根目录
  • Accessing files within the restricted directory.
    Contents of file: [Contents of the file]
    
  • 如果我们未能更改根目录
  • Failed to change root directory.
    

    注意

    • 此函数 chroot() 仅在 GNU 和 BSD 系统以及使用 CLI、CGI 或 Embed SAPI 的系统上可用。此外,此函数需要 root 权限。
    • 调用此函数时,__DIR__ 和 __FILE__ 的魔术常量值保持不变。
    • 由于安全原因,此函数在 Windows 和 MacOS 系统中不支持。

    总结

    PHP 的 chroot() 函数更改根目录并将文件访问权限限制在特定文件夹中以提高安全性。其格式为“chroot(directory)”。成功返回 true,否则返回 false。“chroot('/path/to/rootFolder/')”就是一个例子。

    因此,此函数看起来像是在该文件夹周围建了一堵墙。并且它与 Windows 和 macOS 不兼容。

    php_function_reference.htm
    广告
    © . All rights reserved.