创建多级目录
/**
* 创建多级目录
*
* @param string $dir 目录
* @param string $mode 模式
*
* @return boolean
*/
function mkdirs($dir, $mode = 0777)
{
if (!$dir) {
return false;
}
is_file($dir) and $dir = dirname($dir);
if (is_dir($dir)) {
return true;
}
if (mkdir($dir, $mode, true)) {
clearstatcache();
return true;
}
if (!mkdir($dir, $mode)) {
return false;
}
if (!mkdirs(dirname($dir), $mode)) {
return false;
}
(is_dir($dir) or $re = mkdir($dir, $mode)) and clearstatcache();
return $re;
}
读文件
/**
* 读取文件内容
*
* @param string $file 文件
*
* @return string|false
*/
function readFromFile($file)
{
if (!is_file($file)) {
return false;
}
if (function_exists('file_get_contents')) {
return file_get_contents($file);
}
if (($fp = @fopen($file, 'rb')) !== false) {
flock($fp, LOCK_EX);
$data = fread($fp, filesize($file));
flock($fp, LOCK_UN);
fclose($fp);
return $data;
}
return '';
}
写文件
/**
* 写入文件
*
* @param string $file 文件名
* @param mixed $text 内容
* @param string $mode 读写模式
*
* @return int
*/
function writeToFile($file, $text = null, $mode = 'wb')
{
$bytes = 0;
if (!$file || !mkdirs(dirname($file))) {
return $bytes;
}
if (function_exists('file_put_contents')) {
return file_put_contents($file, $text, stripos($mode, 'a') !== false ? FILE_APPEND : LOCK_EX) ?: 0;
}
if (($fp = fopen($file, $mode)) !== false) {
flock($fp, LOCK_EX);
$bytes = fwrite($fp, $text);
flock($fp, LOCK_UN);
fclose($fp);
}
clearstatcache();
return $bytes ? $bytes : 0;
}