温馨提示×

php怎么创建文件夹并写入内容

PHP
小亿
85
2024-03-16 20:18:53
栏目: 编程语言

在PHP中创建文件夹并写入内容可以使用以下代码:

<?php
$folderPath = 'path/to/folder'; // 文件夹路径
$fileName = 'file.txt'; // 文件名
$fileContent = 'Hello, World!'; // 写入的内容

// 创建文件夹
if (!file_exists($folderPath)) {
    mkdir($folderPath, 0777, true);
}

// 创建文件并写入内容
$file = fopen($folderPath . '/' . $fileName, 'w');
fwrite($file, $fileContent);
fclose($file);

echo 'File created and content written successfully.';
?>

在上面的代码中,首先指定了要创建文件夹的路径、要创建的文件名和要写入的内容。然后通过mkdir()函数创建文件夹(如果文件夹不存在的话),然后通过fopen()函数创建文件并指定写入模式为'w',最后通过fwrite()函数写入文件内容,最后通过fclose()函数关闭文件。最后输出一个成功的消息。

0