【发布时间】:2012-03-17 09:09:54
【问题描述】:
我正在尝试编写一个简单的 PHP 脚本,将字符串写入 .txt 文件。 简单的。为此,我有这个:
<?php
if(isset(isset($_GET["fileName"]) == true && isset($_GET["output"]) == true){
$fp = fopen($_GET["fileName"], "a+");
if($fp !== null){
fputs($fp, $_GET["output"] . "\r\n");
fclose($fp);
}
}
?>
但我确实需要能够保存到特定位置,所以我写了这个:
<?php
if(isset($_GET["filePath"]) == true && isset($_GET["fileName"]) == true && isset($_GET["output"]) == true){
$fp = fopen($_GET["filePath"] . $_GET["fileName"], "a+");
if($fp !== null){
fputs($fp, $_GET["output"] . "\r\n");
fclose($fp);
}
}
?>
当然,这行不通。
1. 如何使用 PHP 保存到特定位置?
2.这个路径可以是相对路径吗? (我只是发送“/output/”,保存会按预期完成)。
谢谢。
现在我在这里:
<?php
if(isset($_GET["filePath"]) && isset($_GET["fileName"]) && isset($_GET["output"])){
$filename=preg_replace('/[^a-z0-9]/i', '', $_GET['fileName']).'.txt';
$filepathSanitized='http://thepathtomywebsite/~subdomain/'.$_GET["filePath"].$filename;
echo $filepathSanitized; // i get the correct path, but no file is present there
$fp = fopen($_GET["filepathSanitized"], "a+");
if($fp !== null){
fputs($fp, $_GET["output"] . "\r\n");
fclose($fp);
}
else echo ('Something wrong'); // it never gets to this
}
?>
我这样称呼上面的:
$.get("save_me.php", { filePath: "demo/", fileName: "text", output: 'thing to write into' });
但是没有创建文件。我不知道要调试什么才能找出问题所在。 谢谢。
【问题讨论】:
-
您嵌套的
isset()毫无意义,而且闻起来像是会导致致命错误的东西。除此之外,你真的不需要== true每次。这是隐含的,添加它只会使您的代码膨胀。 -
嵌套的 isset().. 这难道不能帮助我检查是否发送了某些东西吗?我认为这是正确的做法。谢谢。