/system/helpers/file_helper.php CI文件助手

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package		CodeIgniter
 * @author		ExpressionEngine Dev Team
 * @copyright	Copyright (c) 2008 - 2011, EllisLab, Inc.
 * @license		http://codeigniter.com/user_guide/license.html
 * @link		http://codeigniter.com
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * CodeIgniter File Helpers
 * CI文件助手
 * 
 * @package		CodeIgniter
 * @subpackage	Helpers
 * @category	Helpers
 * @author		ExpressionEngine Dev Team
 * @link		http://codeigniter.com/user_guide/helpers/file_helpers.html
 */

// ------------------------------------------------------------------------

/**
 * Read File
 * 读取文件
 * 
 * Opens the file specfied in the path and returns it as a string.
 * 打开文件,而指定路径中,它作为一个字符串返回。
 * 
 * @access	public
 * @param	string	path to file
 * @return	string
 */
if ( ! function_exists('read_file'))
{
	function read_file($file)
	{
		//文件不存在
		if ( ! file_exists($file))
		{
			return FALSE;
		}

		//查看是否支持file_get_contents();
		if (function_exists('file_get_contents'))
		{
			return file_get_contents($file);
		}

		//如果文件打开失败
		if ( ! $fp = @fopen($file, FOPEN_READ))
		{
			return FALSE;
		}

		//锁定文件
		flock($fp, LOCK_SH);

		$data = '';
		//如果文件的大于0
		if (filesize($file) > 0)
		{
			//开始读取,fread($fp,filesize($file));
			//注意,这里返回的是一个引用
			$data =& fread($fp, filesize($file));
		}
        //解锁定
		flock($fp, LOCK_UN);
		fclose($fp); //关闭文件流

		return $data;
	}
}

// ------------------------------------------------------------------------

/**
 * Write File
 * 写入文件
 * 
 * Writes data to the file specified in the path.
 * Creates a new file if non-existent.
 * 将数据写入到指定的文件路径中。
 * 创建一个新的文件,如果不存在。
 * @access	public
 * @param	string	path to file
 * @param	string	file data
 * @return	bool
 */
if ( ! function_exists('write_file'))
{
	//$path: 路径
	//$data: 内容
	//$mode: FOPEN_WRITE_CREATE_DESTRUCSTIVE
	// define('FOPEN_WRITE_CREATE_DESTRUCTIVE',		'wb'); 
	function write_file($path, $data, $mode = FOPEN_WRITE_CREATE_DESTRUCTIVE)
	{
		//如果该路径打开失败
		if ( ! $fp = @fopen($path, $mode))
		{
			return FALSE;
		}

		//锁定文件flock($fp,LOCK_EX)
		flock($fp, LOCK_EX);
		fwrite($fp, $data);
		flock($fp, LOCK_UN); //解锁
		fclose($fp); //关闭

		return TRUE;
	}
}

// ------------------------------------------------------------------------

/**
 * Delete Files
 * 删除文件
 * 
 * Deletes all files contained in the supplied directory path.
 * Files must be writable or owned by the system in order to be deleted.
 * If the second parameter is set to TRUE, any directories contained
 * within the supplied base directory will be nuked as well.
 * 删除所提供的目录路径中包含的所有文件。
 * 文件必须是可写的,或由系统拥有以被删除。
 * 如果第二个参数设置为TRUE,任何目录中包含提供的基本目录内将被NUKE掉。
 * @access	public
 * @param	string	path to file
 * @param	bool	whether to delete any directories found in the path
 *                  是否要删除任何目录路径中找到 
 * @return	bool
 */
if ( ! function_exists('delete_files'))
{
	function delete_files($path, $del_dir = FALSE, $level = 0)
	{
		// Trim the trailing slash
		// 剪裁尾随斜线
		// rtrim($path)在$path中去掉系统的目录 链接符

		
		$path = rtrim($path, DIRECTORY_SEPARATOR);

		if ( ! $current_dir = @opendir($path))
		{
			return FALSE;
		}

		//开始读取文件
		while (FALSE !== ($filename = @readdir($current_dir)))
		{
			//文件不为. 或者..
			if ($filename != "." and $filename != "..")
			{
				//如果为目录 
				if (is_dir($path.DIRECTORY_SEPARATOR.$filename))
				{
					// Ignore empty folders 忽略空文件夹
					if (substr($filename, 0, 1) != '.')
					{
						//将递归的及别加一
						delete_files($path.DIRECTORY_SEPARATOR.$filename, $del_dir, $level + 1);
					}
				}
				else
				{
					//删除文件
					unlink($path.DIRECTORY_SEPARATOR.$filename);
				}
			}
		}
		@closedir($current_dir); //closedir($current_dir);

		//如果要删除目录,并且递归的级别大小0
		if ($del_dir == TRUE AND $level > 0)
		{
			return @rmdir($path); //删除目录 
		}

		return TRUE;
	}
}

// ------------------------------------------------------------------------

/**
 * Get Filenames
 * 获取文件名
 * 
 * Reads the specified directory and builds an array containing the filenames.
 * Any sub-folders contained within the specified path are read as well.
 * 
 * 读取指定的目录和构建一个数组,包含文件名的。
 * 任何指定的路径内包含的子文件夹都读。

 * @access	public
 * @param	string	path to source 路径源
 * @param	bool	whether to include the path as part of the filename
 *                  是否包括作为文件名的一部分的路径
 * @param	bool	internal variable to determine recursion status - do not use in calls
 *                  内部变量来确定递归的状态 - 不使用通话
 * @return	array
 */
if ( ! function_exists('get_filenames'))
{
	function get_filenames($source_dir, $include_path = FALSE, $_recursion = FALSE)
	{
		static $_filedata = array();

		if ($fp = @opendir($source_dir)) 
		{
			
			// reset the array and make sure $source_dir has a trailing slash on the initial call
			// 重置阵列和确保$ SOURCE_DIR有尾随斜线初始呼叫
			if ($_recursion === FALSE)
			{
				$_filedata = array();
				//realpath 返回垃规范的绝对路径名
				//echo realpath('./../../etc/passwd');
				//输出 /etc/passwd
			    // realpath()只有在文件目录存在的情况才返回规范后的绝对路径,如果不存在直接返回false
				$source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
			}

			//开始读取文件
			while (FALSE !== ($file = readdir($fp)))
			{
				//如果为目录 如果文件名为strncmp将$file与.进行对比
				//strncmp()第三个参数是比较的长度 
				if (@is_dir($source_dir.$file) && strncmp($file, '.', 1) !== 0)
				{
					get_filenames($source_dir.$file.DIRECTORY_SEPARATOR, $include_path, TRUE);
				}
				elseif (strncmp($file, '.', 1) !== 0)
				{
					$_filedata[] = ($include_path == TRUE) ? $source_dir.$file : $file;
				}
			}
			return $_filedata;
		}
		else
		{
			return FALSE;
		}
	}
}

// --------------------------------------------------------------------

/**
 * Get Directory File Information
 * 目录文件信息
 * 
 * Reads the specified directory and builds an array containing the filenames,
 * filesize, dates, and permissions
 * 读取指定的目录中建立一个数组,包含文件名,
 * 文件大小,日期和权限
 *
 * Any sub-folders contained within the specified path are read as well.
 * 读取以及任何指定的路径内包含的子文件夹。
 * 
 * @access	public
 * @param	string	path to source 目录路径
 * @param	bool	Look only at the top level directory specified? 看看只在指定的顶级目录?
 * @param	bool	internal variable to determine recursion status - do not use in calls
 *                  内部变量来确定递归的状态 - 不使用通话
 * @return	array
 */
if ( ! function_exists('get_dir_file_info'))
{
	function get_dir_file_info($source_dir, $top_level_only = TRUE, $_recursion = FALSE)
	{
		static $_filedata = array();  //定义一个保存文件数据
		$relative_path = $source_dir; //

		//开打目录 
		if ($fp = @opendir($source_dir))
		{
			// reset the array and make sure $source_dir has a trailing slash on the initial call
			// 重置阵列确保$ SOURCE_DIR有尾随斜线初始呼叫
			if ($_recursion === FALSE)
			{
				$_filedata = array();
				$source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
			}

			// foreach (scandir($source_dir, 1) as $file) // In addition to being PHP5+, scandir() is simply not as fast
			while (FALSE !== ($file = readdir($fp)))
			{
				//如果为目录,进行递归
				if (@is_dir($source_dir.$file) AND strncmp($file, '.', 1) !== 0 AND $top_level_only === FALSE)
				{
					get_dir_file_info($source_dir.$file.DIRECTORY_SEPARATOR, $top_level_only, TRUE);
				}
				//获取文件信息
				elseif (strncmp($file, '.', 1) !== 0)
				{
					$_filedata[$file] = get_file_info($source_dir.$file);
					$_filedata[$file]['relative_path'] = $relative_path;
				}
			}

			return $_filedata;
		}
		else
		{
			return FALSE;
		}
	}
}

// --------------------------------------------------------------------

/**
* Get File Info
* 获取文件详细信息
* 
* Given a file and path, returns the name, path, size, date modified
* Second parameter allows you to explicitly declare what information you want returned
* Options are: name, server_path, size, date, readable, writable, executable, fileperms
* Returns FALSE if the file cannot be found.
* 文件和路径,返回的名称,路径,大小,修改日期
* 第二个参数,可以明确地宣布你想要什么样的信息返回
* 选项是:名称,server_path,大小,日期,可读,可写,可执行,fileperms
* 返回FALSE如果无法找到该文件。
* @access	public
* @param	string	path to file
* @param	mixed	array or comma separated string of information returned
* @return	array
*/
if ( ! function_exists('get_file_info'))
{
	function get_file_info($file, $returned_values = array('name', 'server_path', 'size', 'date'))
	{
        //$returned_values 数组为需要获取文件的那些属性
		if ( ! file_exists($file))
		{
			return FALSE;
		}

		if (is_string($returned_values))
		{
			$returned_values = explode(',', $returned_values);
		}

		foreach ($returned_values as $key)
		{
			switch ($key)
			{
				case 'name': //如称
					$fileinfo['name'] = substr(strrchr($file, DIRECTORY_SEPARATOR), 1);
					break;
				case 'server_path': //保存的路径
					$fileinfo['server_path'] = $file;
					break;
				case 'size': //文件大小
					$fileinfo['size'] = filesize($file);
					break;
				case 'date': //日期
					$fileinfo['date'] = filemtime($file);
					break;
				case 'readable': //可读
					$fileinfo['readable'] = is_readable($file);
					break;
				case 'writable': //
					// There are known problems using is_weritable on IIS.  It may not be reliable - consider fileperms()
					// 一些已知问题用is_weritable在IIS。它可能是不可靠的 - 考虑fileperms()
					$fileinfo['writable'] = is_writable($file);
					break;
				case 'executable': //是否为可执行文件
					$fileinfo['executable'] = is_executable($file);
					break;
				case 'fileperms': //文件的权限
					$fileinfo['fileperms'] = fileperms($file);
					break;
			}
		}

		return $fileinfo;
	}
}

// --------------------------------------------------------------------

/**
 * Get Mime by Extension
 * 获取MIME扩展
 * 
 * Translates a file extension into a mime type based on config/mimes.php.
 * Returns FALSE if it can't determine the type, or open the mime config file
 * 翻译成的基础上config/ mimes.php中mime类型的文件扩展名。
 * 返回FALSE,如果它不能确定类型,或者打开config文件的mime
 * 
 * Note: this is NOT an accurate way of determining file mime types, and is here strictly as a convenience
 * It should NOT be trusted, and should certainly NOT be used for security
 * 注:这是不是一个准确的方法确定文件的MIME类型,是这里严格作为一种方便
 * 它不应该被信任,当然不应该用于安全
 * 
 * @access	public
 * @param	string	path to file
 * @return	mixed
 */
if ( ! function_exists('get_mime_by_extension'))
{
	function get_mime_by_extension($file)
	{
		$extension = strtolower(substr(strrchr($file, '.'), 1));

		global $mimes;

		//加载 mimes文件
		if ( ! is_array($mimes))
		{
			if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
			{
				include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php');
			}
			elseif (is_file(APPPATH.'config/mimes.php'))
			{
				include(APPPATH.'config/mimes.php');
			}

			if ( ! is_array($mimes))
			{
				return FALSE;
			}
		}

		//判断该类型是否在mimes数组中
		if (array_key_exists($extension, $mimes))
		{
			if (is_array($mimes[$extension]))
			{
				// Multiple mime types, just give the first one
				// 多个MIME类型,只给第一个
				return current($mimes[$extension]);
			}
			else
			{
				return $mimes[$extension];
			}
		}
		else
		{
			return FALSE;
		}
	}
}

// --------------------------------------------------------------------

/**
 * Symbolic Permissions
 * 权限符号
 * 
 * Takes a numeric value representing a file's permissions and returns
 * standard symbolic notation representing that value
 * 以一个数值代表一个文件的权限和回报
 * 标准的符号,表示该值
 * @access	public
 * @param	int
 * @return	string
 * 与一个十六进制进行与操作,然后对比一下,
 */
if ( ! function_exists('symbolic_permissions'))
{
	function symbolic_permissions($perms)
	{
		if (($perms & 0xC000) == 0xC000)
		{
			$symbolic = 's'; // Socket
		}
		elseif (($perms & 0xA000) == 0xA000)
		{
			$symbolic = 'l'; // Symbolic Link
		}
		elseif (($perms & 0x8000) == 0x8000)
		{
			$symbolic = '-'; // Regular
		}
		elseif (($perms & 0x6000) == 0x6000)
		{
			$symbolic = 'b'; // Block special
		}
		elseif (($perms & 0x4000) == 0x4000)
		{
			$symbolic = 'd'; // Directory
		}
		elseif (($perms & 0x2000) == 0x2000)
		{
			$symbolic = 'c'; // Character special
		}
		elseif (($perms & 0x1000) == 0x1000)
		{
			$symbolic = 'p'; // FIFO pipe
		}
		else
		{
			$symbolic = 'u'; // Unknown
		}

		// Owner
		$symbolic .= (($perms & 0x0100) ? 'r' : '-');
		$symbolic .= (($perms & 0x0080) ? 'w' : '-');
		$symbolic .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-'));

		// Group
		$symbolic .= (($perms & 0x0020) ? 'r' : '-');
		$symbolic .= (($perms & 0x0010) ? 'w' : '-');
		$symbolic .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-'));

		// World
		$symbolic .= (($perms & 0x0004) ? 'r' : '-');
		$symbolic .= (($perms & 0x0002) ? 'w' : '-');
		$symbolic .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-'));

		return $symbolic;
	}
}

// --------------------------------------------------------------------

/**
 * Octal Permissions
 * 八进制权限
 * Takes a numeric value representing a file's permissions and returns
 * a three character string representing the file's octal permissions
 * 以一个数值代表一个文件的权限和回报
 * 三个字符的字符串,代表文件的八进制权限
 * @access	public
 * @param	int
 * @return	string
 */
if ( ! function_exists('octal_permissions'))
{
	function octal_permissions($perms)
	{
		return substr(sprintf('%o', $perms), -3);
	}
}


/* End of file file_helper.php */
/* Location: ./system/helpers/file_helper.php */

  

posted @ 2013-06-07 18:18  简单--生活  阅读(470)  评论(0编辑  收藏  举报
简单--生活(CSDN)