问题描述
我有一个简单的PHP脚本,可以将文件写入到目录中,但需要将其写入名为"temp"的目录中.
I have a simple PHP script that writes a file into directory where located, but need to have it written into a directory called "temp".
关于这个问题,这里有很多答案,但是似乎找不到我需要的东西.已经审查了http://us2.php.net/manual/zh-CN/function.fwrite.php,但没有运气.
There are many answers here on the subject, but can't seem to find what I need. Have reviewedhttp://us2.php.net/manual/en/function.fwrite.php with no luck.
这是不带表单部分的基本PHP:
Here is the basic PHP without the form part:
<?php
function saveFile($filename,$filecontent){
if (strlen($filename)>0){
$file = @fopen($filename,"w");
if ($file != false){
fwrite($file,$filecontent);
fclose($file);
return 1;
}
return -2;
}
return -1;
}
?>
它显示在/form标签下面:
This appears below the /form tag:
<?php
if (isset($_POST['submitBtn'])){
$filename = (isset($_POST['filename'])) ? $_POST['filename'] : '' ;
$filecontent = (isset($_POST['filecontent'])) ? $_POST['filecontent'] : '' ;
?>
然后:
<?php
if (saveFile($filename,$filecontent) == 1){
echo "<tr><td><br/>File was saved!<br/><br/></td></tr>";
} else if (saveFile($filename,$filecontent) == -2){
echo "<tr><td><br/>An error occured during saving file!<br/><br/></td></tr>";
} else if (saveFile($filename,$filecontent) == -1){
echo "<tr><td><br/>Wrong file name!<br/><br/></td></tr>";
}
?>
感谢您的输入.
推荐答案
您应该检查该文件夹是否存在,如果不存在,请创建该文件夹.您的代码应如下所示:
You should check that folder exists and if not to create it. Your code should look like:
<?php
function saveFile($filename,$filecontent){
if (strlen($filename)>0){
$folderPath = 'temp';
if (!file_exists($folderPath)) {
mkdir($folderPath);
}
$file = @fopen($folderPath . DIRECTORY_SEPARATOR . $filename,"w");
if ($file != false){
fwrite($file,$filecontent);
fclose($file);
return 1;
}
return -2;
}
return -1;
}
?>
我还改进了代码的另一部分,以避免在出现问题时多次调用该函数.
Also I've improved another part of your code to avoid multiple calls to the function if something goes wrong.
<?php
$fileSavingResult = saveFile($filename, $filecontent);
if ( fileSavingResult == 1){
echo "<tr><td><br/>File was saved!<br/><br/></td></tr>";
} else if (fileSavingResult == -2){
echo "<tr><td><br/>An error occured during saving file!<br/><br/></td></tr>";
} else if (fileSavingResult == -1){
echo "<tr><td><br/>Wrong file name!<br/><br/></td></tr>";
}
?>
这篇关于使用fwrite将文件保存到新目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!