导航首页 » 技术教程 » php文件包含目录配置open_basedir的使用与性能详解
php文件包含目录配置open_basedir的使用与性能详解 120 2024-01-10   

1.open_basedir介绍

open_basedir 将php所能打开的文件限制在指定的目录树中,包括文件本身。当程序要使用例如fopen()或file_get_contents()打开一个文件时,这个文件的位置将会被检查。当文件在指定的目录树之外,程序将拒绝打开。

本指令不受安全模式打开或关闭的影响。

2.open_basedir设置方法

1.在php.ini 加入

open_basedir="指定目录"

2.在程序中使用

ini_set('open_basedir', '指定目录');

但不建议使用这种方法

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

php_admin_value open_basedir "指定目录"
httpd.conf中的VritualHost

php_admin_value open_basedir "指定目录"

4.nginx fastcgi.conf

fastcgi_param PHP_VALUE "open_basedir=指定目录"

用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>

在上一层目录 /home/fdipzone/sites/ 中创建一个test.txt文件,在in.fdipzone.com中创建php执行以下代码

<?php
echo file_get_contents('../test.txt');
?>

因为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 msrn", ((float)($endtime)-(float)($starttime))*1000);

function getMicrotime(){
  list($usec, $sec) = explode(' ', microtime());
  return (float)$usec + (float)$sec;
}
?>

关闭open_basedir测试

run time 137.237072 ms

打开open_basedir测试

run time 404.207945 ms

开启open_basedir后,执行时间是关闭的3倍。

总结:使用open_basedir可以限制程序可操作的目录和文件,提高系统安全性。但会影响I/O性能导致系统执行变慢,因此需要根据具体需求,在安全与性能上做平衡。

以上这篇php文件包含目录配置open_basedir的使用与性能详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持绿夏网。



!!!站长长期在线接!!!

网站、小程序:定制开发/二次开发/仿制开发等

各种疑难杂症解决/定制接口/定制采集等

站长微信:lxwl520520

站长QQ:1737366103