在php中创建文件并写入文件

时间:2018-08-18 10:17:30

标签: php

我想创建一个名为info.php的文件。我正在使用xampp服务器,这是我的代码:

<?
if (file_exists('./info.php')) {
header('Location: ./public/index.php');
exit();
}else{

fopen('info.php', 'c');
$handle = fopen('info.php' , 'w+') or die('Unable to create file');

$username = "$username =" .$_POST['Username'];
$password = "$pass = " .$_POST['password'];
$webname = "$wbname = " .$_POST['webname'];
$webtitle = "$wbtit = " .$_POST['webtitle'];

fwrite($handle, '<?');
fwrite($handle, $username);
fwrite($handle, $password);
fwrite($handle, $webname);
fwrite($handle, $webtitle);
fclose();
}

我还阅读了PHP手册,并尝试了w3schools代码,但还是一无所获。

3 个答案:

答案 0 :(得分:1)

if (file_exists('./info.php')) {
header('Location: ./public/index.php');
exit();
}else{
    $handle = fopen('info.php', 'w');

    $username = "$username =" .$_POST['Username'];
    $password = "$pass = " .$_POST['password'];
    $webname = "$wbname = " .$_POST['webname'];
    $webtitle = "$wbtit = " .$_POST['webtitle'];

    fwrite($handle, '<?');
    fwrite($handle, $username);
    fwrite($handle, $password);
    fwrite($handle, $webname);
    fwrite($handle, $webtitle);
    fclose($handle);
}

此代码运行正常。您只需要像这样设置文件夹的写访问权限:

sudo chmod -R 777 FOLDER_NAME/   - using terminal 

答案 1 :(得分:0)

您可以尝试使用此代码。

<?php

if (file_exists('./info.php')) {
header('Location: ./public/index.php');
exit();
}else{
$handle = fopen('info.php' , 'w+') or die('Unable to create file');

$username = '$username ="' .$_POST['Username'].'";';
$password = '$pass = "' .$_POST['password'].'";';
$webname = '$wbname = "' .$_POST['webname'].'";';
$webtitle = '$wbtit = "' .$_POST['webtitle'].'";';

fwrite($handle, '<?php ');
fwrite($handle, $username);
fwrite($handle, $password);
fwrite($handle, $webname);
fwrite($handle, $webtitle);
fwrite($handle, ' ?>');
fclose($handle);
}
?>

答案 2 :(得分:-2)

以此替换您的代码,希望它能起作用

if (file_exists('./info.php')) {
header('Location: ./public/index.php');
exit();
}else{
    $handle = fopen('info.php', 'w');

    $username = "$username =" .$_POST['Username'];
    $password = "$pass = " .$_POST['password'];
    $webname = "$wbname = " .$_POST['webname'];
    $webtitle = "$wbtit = " .$_POST['webtitle'];

    fwrite($handle, '<?');
    fwrite($handle, $username);
    fwrite($handle, $password);
    fwrite($handle, $webname);
    fwrite($handle, $webtitle);
    fclose($handle);
}