本文共 2569 字,大约阅读时间需要 8 分钟。
PHP 提供了丰富的文件操作函数,能够帮助开发者高效处理文件相关事务。本文将详细介绍 PHP 中的核心文件函数及其应用示例。
PHP 提供多种函数用于获取文件的路径信息:
示例:
$str = 'E:\phpStudy\PHPTutorial\WWW\index.php';echo basename($str); // 输出: index.php$str = 'E:\phpStudy\PHPTutorial\WWW\index.php';echo dirname($str); // 输出: E:\phpStudy\PHPTutorial\WWWprint_r(pathinfo($str)); // 输出:// Array// (// [dirname] => E:\phpStudy\PHPTutorial\WWW// [basename] => index.php// [extension] => php// [filename] => index// )
PHP 提供了多种文件操作函数,适用于不同的场景:
文件下载是常见的Web应用需求,以下是实现文件下载的三种方法:
// 示例文件路径$file = '1.txt';if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . basename($file) . '"]'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); readfile($file); exit;} // 示例文件路径$file = '1.txt';if (file_exists($file)) { $fp = fopen($file, "r"); $file_size = filesize($file); $file_name = basename($file); // 发送下载所需的HTTP头文件 header("Content-type: application/octet-stream"); header("Accept-Ranges: bytes"); header("Accept-Length: " . $file_size); header("Content-Disposition: attachment; filename=" . $file_name); echo fread($fp, $file_size); fclose($fp); exit;} function DownloadFile($file) { // 示例文件路径(带路径信息) if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($file) . ''); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; }} 除了上述函数,PHP 还提供了其他文件操作功能,例如:
这些函数在日常开发中广泛应用,能够帮助开发者高效管理文件。
通过上述方法,可以轻松实现文件的下载、操作和管理。PHP 提供的丰富函数使得文件处理变得简单易学。
转载地址:http://qwtfk.baihongyu.com/