file_exists() 是 PHP 中的一个内置函数,用于检查指定的文件或目录是否存在。要有效地使用它,请遵循以下步骤:
\,在 Unix 和 Linux 上是 /)。$filepath = 'path/to/your/file.txt'; file_exists() 函数检查文件或目录是否存在。if (file_exists($filepath)) { echo "文件存在"; } else { echo "文件不存在"; } if (file_exists($filepath)) { // 读取文件内容 $content = file_get_contents($filepath); echo $content; } else { // 创建一个新文件 $newfile = fopen($filepath, 'w'); if ($newfile) { fclose($newfile); echo "文件已创建"; } else { echo "无法创建文件"; } } file_exists() 函数的第二个参数设置为 true。$dirpath = 'path/to/your/directory'; if (file_exists($dirpath) && is_dir($dirpath)) { echo "目录存在"; } else { echo "目录不存在"; } 注意:在使用 file_exists() 时,请确保考虑到安全性问题,例如路径遍历攻击。避免使用用户提供的路径直接访问系统文件。在执行任何文件操作之前,始终验证和清理用户输入。