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
    廣告