open_basedir限制目錄


 

 

 

 

 

1.open_basedir介紹

前言:前些日我用lnmp一鍵安裝包出現了open_basedir的問題,因為我把項目目錄變了,所以要在的fastcgi.conf下面加上open_basedir的目錄

 

open_basedir 將PHP所能打開的文件限制在指定的目錄樹中,包括文件本身。當程序要使用例如fopen()file_get_contents()打開一個文件時,這個文件的位置將會被檢查。當文件在指定的目錄樹之外,程序將拒絕打開。

本指令不受安全模式打開或關閉的影響。 

2.open_basedir設置方法

1.在php.ini 加入

open_basedir="指定目錄"
  • 1
  • 1

2.在程序中使用

ini_set('open_basedir', '指定目錄');
  • 1
  • 1

但不建議使用這種方法

3.在apache的httpd.conf中的Directory配置

php_admin_value open_basedir "指定目錄"
  • 1
  • 1

httpd.conf中的VritualHost

php_admin_value open_basedir "指定目錄"
  • 1
  • 1

4.nginx fastcgi.conf

fastcgi_param PHP_VALUE "open_basedir=指定目錄"
  • 1
  • 1

用open_basedir指定的限制實際上是前綴,不是目錄名。 
也就是說 open_basedir=/home/fdipzone 也會允許訪問/home/fdipzone_abc,如果要將訪問限制為目錄,請使用斜線結束路徑名,例如:open_basedir=”/home/fdipzone/”

如果要設置多個目錄,window使用;分隔目錄,Linux使用:分隔目錄。 

3.使用open_basedir限制目錄訪問

首先創建一個VirtualHost, 
設置open_basedir 為/home/fdipzone/sites/in.fdipzone.com/

<VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /home/fdipzone/sites/in.fdipzone.com ServerName in.fdipzone.com php_admin_value open_basedir "/home/fdipzone/sites/in.fdipzone.com/" <Directory "/home/fdipzone/sites/in.fdipzone.com"> allow from all Options + Indexes </Directory> </VirtualHost>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在上一層目錄 /home/fdipzone/sites/ 中創建一個test.txt文件,在in.fdipzone.com中創建php執行以下代碼

<?php echo file_get_contents('../test.txt'); ?>
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

因為test.txt不在限定的目錄范圍內,因此php提示警告 
Warning: file_get_contents(): open_basedir restriction in effect. File(../test.txt) is not within the allowed path(s): (/home/fdipzone/sites/in.fdipzone.com/) in /home/fdipzone/sites/in.fdipzone.com/index.php on line 3 

4.設置open_basedir的性能分析

open_basedir開啟后會影響I/O,因為每個調用的文件都需要判斷是否在限制目錄內。

測試程序,讀取限制目錄內同一文件10000次

<?php // 記錄開始時間 $starttime = getMicrotime(); // 讀取10000次文件 for($i=0; $i<10000; $i++){ file_get_contents('test.txt'); } // 記錄結束時間 $endtime = getMicrotime(); printf("run time %f ms\r\n", ((float)($endtime)-(float)($starttime))*1000); function getMicrotime(){ list($usec, $sec) = explode(' ', microtime()); return (float)$usec + (float)$sec; } ?>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

關閉open_basedir測試 
run time 137.237072 ms

打開open_basedir測試 
run time 404.207945 ms

開啟open_basedir后,執行時間是關閉的3倍。



總結:使用open_basedir可以限制程序可操作的目錄和文件,提高系統安全性。但會影響I/O性能導致系統執行變慢,因此需要根據具體需求,在安全與性能上做平衡。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM