使用PHP8,实现一个文件类,方便快速的对一个文件进行处理!
要求:使用php8的语法,实现一个文件类,包含:获取文件名、文件大小、文件所在目录、文件大小、文件MIME、下载文件
/**
* 文件类,用于获取文件的相关信息。
*/
class File {
private string $filePath; // 文件路径
/**
* 构造函数,传入文件路径。
*
* @param string $filePath 文件路径
*/
public function __construct(string $filePath) {
$this->setFilePath($filePath); // 使用 setFilePath() 函数设置文件路径
}
/**
* 获取文件路径。
*
* @return string 文件路径
*/
public function getFilePath(): string {
return $this->filePath;
}
/**
* 设置文件路径。
*
* @param string $filePath 文件路径
*/
public function setFilePath(string $filePath): void {
$this->filePath = $filePath;
}
/**
* 获取文件名。
*
* @return string 文件名
*/
public function getFilename(): string {
return basename($this->filePath); // 使用 basename() 函数获取文件名
}
/**
* 获取文件所在目录。
*
* @return string 文件所在目录
*/
public function getDirectory(): string {
return dirname($this->filePath); // 使用 dirname() 函数获取文件所在目录
}
/**
* 获取文件格式。
*
* @return string|false 文件格式,如果无法获取则返回 false
*/
public function getExtension(): string|false {
$pattern = '/\.([a-z0-9]+)$/i'; // 定义正则表达式,用于匹配文件名中的后缀部分
if (preg_match($pattern, $this->getFilename(), $matches)) { // 使用 preg_match() 函数匹配文件名中的后缀部分
return $matches[1]; // 返回匹配结果中的第一个子组,即文件格式
} else {
return false; // 如果无法匹配,则返回 false
}
}
/**
* 获取文件大小。
*
* @return int 文件大小,单位为字节
*/
public function getSize(): int {
return filesize($this->filePath); // 使用 filesize() 函数获取文件大小
}
/**
* 获取文件 MIME 类型。
*
* @return string 文件 MIME 类型
*/
public function getMime(): string {
return mime_content_type($this->filePath); // 使用 mime_content_type() 函数获取文件 MIME 类型
}
/**
* 下载文件到本地。
*
* @param string $savePath 下载文件保存路径
* @return string 下载后的文件名
*/
public function download(string $savePath): string {
if (!file_exists(dirname($savePath))) { // 如果下载路径所在目录不存在,则创建目录
mkdir(dirname($savePath), 0777, true);
}
$fp = fopen($savePath, 'w'); // 打开文件句柄
$ch = curl_init(); // 初始化 curl
curl_setopt($ch, CURLOPT_URL, $this->filePath); // 设置下载文件的 URL
curl_setopt($ch, CURLOPT_FILE, $fp); // 设置文件句柄为 curl 的输出
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 支持重定向
curl_exec($ch); // 执行 curl 下载文件
curl_close($ch); // 关闭 curl
fclose($fp); // 关闭文件句柄
return basename($savePath); // 返回下载后的文件名
}
}