34

我们可以用 PHP 代码创建文件夹吗?我希望每当新用户创建他的新帐户时,他的文件夹会自动创建,并且还会创建一个 PHP 文件。这可能吗?

4

5 回答 5

60

纯粹的基本文件夹创建

<?php mkdir("testing"); ?><= 这个,实际上创建了一个名为“testing”的文件夹。



基本文件创建

<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>

使用aa+开关添加/附加到文件。



编辑:

此版本将同时创建一个文件和文件夹,然后在屏幕上显示。

<?php

// change the name below for the folder you want
$dir = "new_folder_name";

$file_to_write = 'test.txt';
$content_to_write = "The content";

if( is_dir($dir) === false )
{
    mkdir($dir);
}

$file = fopen($dir . '/' . $file_to_write,"w");

// a different way to write content into
// fwrite($file,"Hello World.");

fwrite($file, $content_to_write);

// closes the file
fclose($file);

// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;

?>
于 2013-08-13T19:05:42.990 回答
16

您可以使用mkdir()函数使用 PHP 创建一个目录。

mkdir("/path/to/my/dir", 0700);

您可以使用fopen()在该目录中使用 mode 创建一个文件w

fopen('myfile.txt', 'w');

w : 只供书写;将文件指针放在文件的开头并将文件截断为零长度。如果该文件不存在,请尝试创建它。

于 2013-08-13T18:54:56.647 回答
6

您可以轻松创建它:

$structure = './depth1/depth2/depth3/';
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}
于 2013-08-13T19:00:11.947 回答
2

...然后您可以使用它copy()来复制 PHP 文件,尽管这听起来非常低效。

于 2013-08-13T18:58:22.460 回答
1

为了回答如何在 PHP 中写入文件的问题,您可以使用以下示例:

    $fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
    if ($fp) {
        fwrite ($fp, $text); //$text is what you are writing to the file
        fclose ($fp);
        $writeSuccess = "Yes";
        #echo ("File written");
    }
    else {
    $writeSuccess = "No";
    #echo ("File was not written");
    }
于 2013-08-13T19:04:10.440 回答