欢迎访问宙启技术站
智能推送

初学者必学的10个PHP文件路径处理函数

发布时间:2023-07-01 01:10:19

1. basename() 函数:获取文件路径中的文件名部分。

例如:

$path = '/var/www/html/index.php';

$filename = basename($path);

echo $filename; // 输出 "index.php"

2. dirname() 函数:获取文件路径中的目录部分。

例如:

$path = '/var/www/html/index.php';

$directory = dirname($path);

echo $directory; // 输出 "/var/www/html"

3. realpath() 函数:获取文件路径的绝对路径。

例如:

$path = 'index.php';

$absolute_path = realpath($path);

echo $absolute_path; // 输出 "/var/www/html/index.php"

4. pathinfo() 函数:获取文件路径的详细信息,包括目录名、文件名、文件扩展名等。

例如:

$path = '/var/www/html/index.php';

$path_info = pathinfo($path);

echo $path_info['dirname']; // 输出 "/var/www/html"

echo $path_info['basename']; // 输出 "index.php"

echo $path_info['extension']; // 输出 "php"

5. file_exists() 函数:判断文件是否存在。

例如:

$path = '/var/www/html/index.php';

if (file_exists($path)) {

    echo "文件存在";

} else {

    echo "文件不存在";

}

6. is_file() 函数:判断路径是否为文件。

例如:

$path = '/var/www/html/index.php';

if (is_file($path)) {

    echo "是文件";

} else {

    echo "不是文件";

}

7. is_dir() 函数:判断路径是否为目录。

例如:

$path = '/var/www/html';

if (is_dir($path)) {

    echo "是目录";

} else {

    echo "不是目录";

}

8. file_get_contents() 函数:读取文件内容。

例如:

$path = '/var/www/html/index.php';

$content = file_get_contents($path);

echo $content;

9. file_put_contents() 函数:向文件写入内容。

例如:

$path = '/var/www/html/index.php';

$content = "Hello, world!";

file_put_contents($path, $content);

10. glob() 函数:匹配指定模式的文件路径。

例如:

$files = glob('/var/www/html/*.php');

foreach ($files as $file) {

    echo $file;

}