文件辅助函数
文件辅助函数文件包含若干对文件进行操作的函数。
加载
使用以下代码:
$this->load->helper('file');
加载后可用以下函数:
read_file('path')
返回路径为path的文件内容。例:
$string = read_file('./path/to/file.php');
可以是相对或者绝对的服务器的路径。如果函数执行失败则返回 FALSE(boolean类型)。
提示: 这里的路径是相对于该站点的index.php所在的路径,而不是当前所在的控制器或视图文件的路径。这是因为CodeIgniter使用的前端控制器(front controller)所以,所有的路径永远都是相对于index.php所在路径。
如果你的服务器打开了open_basedir限制,此函数能过以上代码的调用可以无法正常工作。
write_file('path', $data)
写进数据到path所指向文件。如果文件不存在则创建之。例:
$data = 'Some file data';
if ( ! write_file('./path/to/file.php', $data))
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
你可以通过可选的第三个参数来设置文件的读写属性:
write_file('./path/to/file.php', $data, 'r+');
默认读写属性是 wb。更多关于文件读写属性参数的内容请参考:PHP user guide。
注意:要使用此函数写进数据,当前用户对此文件应该是“可写”的,如果该文件不存在则该用户应该对包含该文件的目录有写权限。(即*nux系统下的666,777等)。
提示: 这里的路径是相对于该站点的index.php所在的路径,而不是当前所在的控制器或视图文件的路径。这是因为CodeIgniter使用的前端控制器(front controller)所以,所有的路径永远都是相对于index.php所在路径。
delete_files('path')
删除所有包含于path下的文件。例:
delete_files('./path/to/directory/');
如果第二个参数设为 true, 则所有在path下的文件夹也会被删除掉。例:
delete_files('./path/to/directory/', TRUE);
提示: 要被删除的文件必须是当前系统用户所有或者是当前用户对之具有写权限。
get_filenames('path/to/directory/')
获取path/to/directory目录下所有文件名组成的数组。如果需要文件名中有其完整路径则可以设置可选的第二个参数为TRUE。
get_dir_file_info('path/to/directory/')
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.
get_file_info('path/to/file', $file_information)
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.
Note: The "writable" uses the PHP function is_writable() which is known to have issues on the IIS webserver. Consider using fileperms instead, which returns information from PHP's fileperms() function.
get_mime_by_extension('file')
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.
$file = "somefile.png";
echo $file . ' is has a mime type of ' . get_mime_by_extension($file);
Note: This is not an accurate way of determining file mime types, and is here strictly as a convenience. It should not be used for security.
symbolic_permissions($perms)
Takes numeric permissions (such as is returned by fileperms() and returns standard symbolic notation of file permissions.
echo symbolic_permissions(fileperms('./index.php'));
// -rw-r--r--
octal_permissions($perms)
Takes numeric permissions (such as is returned by fileperms() and returns a three character octal notation of file permissions.
echo octal_permissions(fileperms('./index.php'));
// 644