欢迎来到代码驿站!

PHP代码

当前位置:首页 > 软件编程 > PHP代码

php文件包含目录配置open_basedir的使用与性能详解

时间:2021-04-12 08:54:22|栏目:PHP代码|点击:

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 ms\r\n", ((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结合curl实现多线程抓取

栏    目:PHP代码

下一篇:Codeigniter注册登录代码示例

本文标题:php文件包含目录配置open_basedir的使用与性能详解

本文地址:http://www.codeinn.net/misctech/99798.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有